简体   繁体   中英

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. 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. 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("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.

if you use expressjs, there is a middleware for it call cors . just use app.use(require('cors')) and you will be all set.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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