如何在node.js响应中添加跨域标头

how to add a cross domain header to node.js response

本文关键字:添加 响应 node js      更新时间:2023-09-26

所以我有一个大问题。我需要从我构建的一个小node.js服务器中获取数据,然后使用这些数据。我遇到的问题是,错误表明我不能进行跨域请求,从我所看到的情况来看,我需要为此添加一个标头。我见过很多解决这个问题的方法的例子,但它们都使用express。我尽量远离快递,因为我在一个沙盒里,没有办法添加快递。

--服务器代码-

    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();

--客户端功能——

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

我希望这将是一个简单的解决方案,不会很难做到。

在将响应发送回客户端-之前,可以使用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');

希望能有所帮助。

我已经想好了需要做什么。我试着运行

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

它成功了!除了错误之外,其他方法都没有做任何事情。谢谢你帮我回答这个问题。

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

如果您使用expressjs,则有一个名为cors的中间件。只需使用app.use(require('cors')),您就可以做好一切准备。