gpt4 book ai didi

javascript - Angular $http.post 和没有 'Access-Control-Allow-Origin' header

转载 作者:搜寻专家 更新时间:2023-11-01 00:44:30 25 4
gpt4 key购买 nike

我有两个带有 nodejs 和 angularjs 的应用程序。nodejs 应用程序有一些这样的代码:

require('http').createServer(function(req, res) {


req.setEncoding('utf8');
var body = '';
var result = '';
req.on('data', function(data) {
// console.log("ONDATA");

//var _data = parseInput( data,req.url.toString());
var _data = parseInputForClient(data, req.url.toString());



switch (req.url.toString()) {
case "/cubes":
{

并且此应用程序托管在 http://localhost:4000.angularjs 应用程序托管 Node http-server 模块在 localhost://www.localhost :3030。在我的一个 angularjs 服务中,我有这样的东西:

fetch:function(){
var data = '{somedata:"somedata"}';
return $http.post('http://localhost:4000/cubes',data).success(function(cubes){
console.log(cubes);
});
}

但是当此服务向服务器发送请求时出现此错误:

XMLHttpRequest cannot load http://localhost:4000/cubes. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3030' is therefore not allowed access. 

所以我在网上和 stackoverflow 上搜索一些主题,然后我找到了 thisthis .根据这些主题,我将服务器中的响应 header 更改为如下内容:

res.writeHead(200, {
'Content-Type': 'application/json',
"Access-Control-Allow-Origin": "*"
});
res.end(JSON.stringify(result));

但这不起作用。我尝试使用 firefox、chrome 并使用 Telerik Fiddler Web Debugger 检查请求,但服务器仍未决,我收到访问控制允许来源错误。

最佳答案

您执行 POST 请求,根据 CORS 规范生成预检请求:http://hacks.mozilla.org/2009/07/cross-site-xmlhttprequest-with-cors/https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS

您的服务器还应该响应 OPTIONS 方法(除了 POST),并在那里返回 Access-Control-Allow-Origin

您可以看到这是原因,因为当您的代码在“网络”选项卡(或在 Fiddler 代理调试器)中创建请求时,您应该看到带有 ORIGIN header 的 OPTIONS 请求

关于javascript - Angular $http.post 和没有 'Access-Control-Allow-Origin' header ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23486409/

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