Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
365 views
in Technique[技术] by (71.8m points)

node.js - How can I add CORS-Headers to a static connect server?

I am writing a little demo web server delivering static html,css and javascript. The server looks like

(function () {
    "use strict";

    var http = require("http");
    var connect = require('connect');
    var app = connect()
        .use(connect.logger('dev'))
        .use(connect.static('home'));

    var server = http.createServer(app);
    server.listen(9999, function () {
        console.log('server is listening');
    });
})();

My client side javascript makes ajax calls to a different server. How can I add

Access-Control-Allow-Origin: http://example.com

to my server response, so that the client side javascript can do the ajax call?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Had a bit of trouble figuring this one out since express has spoiled me.

Take a look at enable cors. Basically what you need to be doing is add Access-Control-Allow-Origin to the domain you want to enable cors on. response.setHeaders is perfect for this task.

Another thing to note is that connect has no way to handle routes. If your app needs to have different routes then you will probably have to write logic for each of them and add res headers to the ones on which you want to enable cors. You can use req.url for it.

var http = require("http");
var connect = require('connect');

var app = connect()

    .use(connect.logger('dev'))

    .use(connect.static('home'))

    .use(function(req, res){

    res.setHeader("Access-Control-Allow-Origin", "http://example.com");
    res.end('hello world
');

 });

var server = http.createServer(app);

server.listen(9999, function () {

    console.log('server is listening');
});

This is the response I got in chrome dev tools

HTTP/1.1 200 OK
Access-Control-Allow-Origin: http://example.com
Date: Sat, 15 Jun 2013 16:01:59 GMT
Connection: keep-alive
Transfer-Encoding: chunked

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...