2015-12-03 125 views
0

所以我有一个主要问题。我需要从我构建的小型node.js服务器获取数据,然后使用该数据。我遇到的问题是错误说我无法跨域请求,并且从我所看到的我需要为此添加标头。我见过很多解决这个问题的例子,但他们都使用快递。我试图远离明确,因为我在一个沙箱主机,并没有办法添加快递。如何将一个跨域头添加到node.js响应

--server代码 -

var http = require('http'), 
    url = require('url'); 
var tweets = {"tweets":[]}; 

http.createServer(function (req, res) { 
    query = url.parse(req.url,true).query; 
    var response = {}; 
    //res.end(JSON.stringify(query)); 
    if(query.action){ 
     console.log("Moving on to phase two!"); 
     if(query.action === "read") { 
      console.log("Listing off the posts"); 
      response = tweets; 
     } 
     else { 
     if(query.action === "post"){ 
      if(query.message) { 
      var tweet = {}; 
      tweet.message = query.message; 
      tweets.tweets.push(tweet); 
      response.stat = "All Good!"; 
      } 
     } 
     } 
    } else { 
     response.error = "No Action"; 
    } 
    response.url = req.url; 
    res.write(JSON.stringify(response)); 
    console.log(JSON.stringify(response)); 
    res.end(); 
}).listen(); 

--client function--

function getJSON(url) { 
     var xhr = new XMLHttpRequest(); 
     xhr.open("GET", url, false); 
     xhr.send(); 
     return JSON.parse(xhr.responseText); 
    } 

我希望这将是一个简单的办法,不会是很难做到的。

回答

0

,您将需要在服务器上启用CORS。

如果使用expressjs,有一个中间件调用它cors。只需使用app.use(require('cors')),你就会全部设置。

0

您可以使用res.header发送响应返回给客户端之前设定的CORS头像下面 -

res.header("Access-Control-Allow-Origin", "*"); // restrict it to the required domain 
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS'); 

    // Set custom headers for CORS 
res.header('Access-Control-Allow-Headers', 'Content-type,Accept,X-Access-Token,X-Key'); 

希望它能帮助。

1

我已经想清楚我需要做什么。我试过跑步

res.setHeader("Access-Control-Allow-Origin", "*"); 

它的工作!除了错误,其他方法都没有做任何其他的方法。谢谢你试图帮助我回答这个问题。