gpt4 book ai didi

javascript - 如何将跨域 header 添加到 node.js 响应

转载 作者:行者123 更新时间:2023-11-30 16:26:35 24 4
gpt4 key购买 nike

所以我有一个大问题。我需要从我构建的小型 node.js 服务器获取数据,然后使用该数据。我遇到的问题是错误提示我无法执行跨域请求,据我所知,我需要为此添加一个 header 。我见过许多解决此问题的方法示例,但它们都使用 express。我试图远离 express,因为我在沙盒主机中,没有办法添加 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 header ,如下所示 -

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

希望对您有所帮助。

关于javascript - 如何将跨域 header 添加到 node.js 响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34057284/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com