Javascript Node.Js 错误“请求中不存在‘Access-Control-Allow-Origin’标头”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/37465815/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Node.Js error "No 'Access-Control-Allow-Origin' header is present on the requested"
提问by L1ghtk3ira
This question is similar to others; however there is a difference that makes it very confusing why it is not working.
这个问题与其他问题类似;然而,有一个差异使得它为什么不起作用非常令人困惑。
My JavaScript was calling 6 json files and all worked correctly. In Node.JS I have cors and headers set up as shown below:
我的 JavaScript 正在调用 6 个 json 文件并且一切正常。在 Node.JS 中,我设置了 cors 和 headers,如下所示:
var fs = require('fs');
var http = require("https");
var express = require('express');
var app = express();
var path = require('path');
var http = require("http");
var url = require("url");
var req = require('request')
var pem = require('pem');
var cors = require("cors");
app.use(express.static(path.join(__dirname, '../')));
app.listen(process.env.PORT || 8080);
app.options('*', cors());
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested- With, Content-Type, Accept");
next();
});
app.all('/posts', function(req, res){
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
});
app.get('/', function (req, res) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
res.writeHead(200, {'Content-Type': 'text/plain'});
contents = fs.readFileSync("sliderImages.json", "utf8");
console.log(path.join(__dirname, '/sliderImages.json'));
res.end(contents);
});
All 6 json files are grabbed from the absolute URL path by Node JS. I have made 2 more yesterday and everything was working fine. However, today I made one and implemented the same way and received the following error:
所有 6 个 json 文件都是 Node JS 从绝对 URL 路径中抓取的。我昨天又做了 2 个,一切正常。但是,今天我做了一个并以相同的方式实现并收到以下错误:
No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.
请求的资源上不存在“Access-Control-Allow-Origin”标头。因此,不允许访问 Origin 'null'。
I am implementing each the same way, example:
我正在以相同的方式实现每个,例如:
var base_url = 'http://127.0.0.1:8080';
mainInformationTop();
function mainInformationTop()
{
$.ajax({
type: "GET",
url: base_url + "/api/topInformation.json",
dataType: "json",
success: function(response)
{
var json_obj = response.mainDescription;
var imagesSlider="";
var imagesSliderDescription ="";
for (var i = 0; i< json_obj.length; i++)
{
}
}
,
error: function(jqXHR, textStatus, errorThrown) {
alert(jqXHR.status);
}
})
}
I don't think the json file is relevant but below is my json file:
我不认为 json 文件是相关的,但下面是我的 json 文件:
{"mainDescription":[
{
"display": "my display",
"description" : "my description"
}
]}
I have took out the information in the for loop for testing as well as my append because irrelevant. For some reason it fails and goes to error instead of success. All other calls are set up the same way and work correctly.
我已经取出 for 循环中的信息进行测试以及我的 append 因为无关紧要。由于某种原因,它失败并进入错误而不是成功。所有其他呼叫都以相同的方式设置并正常工作。
回答by Chris Foster
This is a much more simple version of this answerwhich achieves the same effect:
这是这个答案的一个更简单的版本,它实现了相同的效果:
var fs = require('fs');
var express = require('express');
var cors = require('cors');
var app = express();
app.use(cors());
app.use(express.static(path.join(__dirname, '../')));
app.get('/', function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
contents = fs.readFileSync('sliderImages.json', 'utf8');
res.end(contents);
});
app.listen(process.env.PORT || 8080);
回答by L1ghtk3ira
Fixed it.
修复。
var fs = require('fs');
var http = require("https");
var express = require('express');
var app = express();
var path = require('path');
var http = require("http");
var url = require("url");
var req = require('request')
var pem = require('pem');
var cors = require("cors");
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
app.use(express.static(path.join(__dirname, '../')));
app.listen(process.env.PORT || 8080);
app.options('*', cors());
app.all('/*', function (req, res, next) {
res.header("Access-Control-Allow-Origin", "http://localhost:8080");
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
res.header("Access-Control-Allow-Headers", "X-Requested-With, Content-Type");
next();
});
app.get('/', function (req, res) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
res.writeHead(200, {'Content-Type': 'text/plain'});
contents = fs.readFileSync("sliderImages.json", "utf8");
console.log(path.join(__dirname, '/sliderImages.json'));
res.end(contents);
});
Despite what the comments said the only real thing I changed was moving the app.use before everything else. This solved the issue.
尽管评论说的是我改变的唯一真实的事情是在其他一切之前移动 app.use。这解决了这个问题。
回答by Nandha Kumar
I also suffer this problem the code was as same as above but we want to put the code in starting point. dont put this code in last that means before (res.end()) sending response to client. Three methods (GET,POST,HEAD) that allowed you when you put this code anywhere i think but for other method try this and try with other modules like cors,express but i used http module only
我也遇到这个问题,代码和上面一样,但我们想把代码放在起点。不要将此代码放在最后,这意味着在 (res.end()) 向客户端发送响应之前。三种方法(GET、POST、HEAD)允许你把这段代码放在我认为的任何地方,但对于其他方法试试这个并尝试使用其他模块,如 cors、express 但我只使用了 http 模块
var server=http.createServer(function (req, res) {
res.setHeader("Access-Control-Allow-Origin","*");
res.setHeader("Access-Control-Allow-Methods","PUT,GET,DELETE,PATCH")
res.setHeader('Access-Control-Allow-Credentials', true)
res.setHeader('Access-Control-Allow-Headers','X-Requested-With,content-type,Origin,Accept,Authorization')
// your other code followes