简体   繁体   English

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

[英]how to add a cross domain header to node.js response

So i have a major problem. 所以我有一个大问题。 I need to get data from a little node.js server that i built and then use that data. 我需要从我构建的小型node.js服务器中获取数据,然后使用该数据。 the problem that i am having is that the error says that i can't do cross domain requests and from what i have seen i need to add a header for that. 我遇到的问题是该错误表明我无法执行跨域请求,而从我所看到的情况来看,我需要为此添加标题。 i have seen many exampled of ways to fix this but they all use express. 我已经看到许多解决此问题的方法示例,但是它们都使用express。 I am trying to stay away from express because i am in a sand-boxed host and there is not a way to add express. 我试图远离快递,因为我身处沙盒主机中,并且没有添加快递的方法。

--server code-- -服务器代码-

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

I am hoping that it would be an easy fix that won't be to hard to do. 我希望这将是一个容易解决的问题,而且不会很难。

You can use res.header to set the CORS header like below before sending the response back to client - 您可以使用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');

Hope it helps. 希望能帮助到你。

i have figured out what i needed to do. 我已经知道我需要做什么。 I tryed running 我尝试跑步

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

and it worked! 而且有效! none of the other methods did anything except for error. 除错误外,其他方法均未执行任何操作。 thank you for trying to help me answer the question. 感谢您尝试帮助我回答问题。

you will need to enable CORS on your server. 您将需要在服务器上启用CORS。

if you use expressjs, there is a middleware for it call cors . 如果使用expressjs,则有一个名为cors的中间件。 just use app.use(require('cors')) and you will be all set. 只需使用app.use(require('cors'))就可以了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM