簡體   English   中英

如何在node.js響應中添加跨域標頭

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

所以我有一個大問題。 我需要從我構建的小型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'))就可以了。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM