我知道这感觉像是一个重复的问题,但我已经尝试了所有可能的方法来使我的 ajax 请求起作用,但它就是做不到。这是ajax代码。 ajax 调用是从 index.html 中的 js 文件触发的
self.getJSON = () => {
$.ajax({
type: 'POST',
url: 'https://iot-backend-metropolia.herokuapp.com/api/user' ,
contentType: 'application/json; charset=utf-8',
dataType: "json",
})
.done(function(result) {
console.log(result);
})
.fail(function(xhr, status, error) {
alert(error);
})
.always(function(data){
});
}
我尝试了两种方法。
1) npm install cors
app.use(cors())
2) // Add headers
app.use(function (req, res, next) {
// Website you wish to allow to connect
res.setHeader('Access-Control-Allow-Origin', 'http://localhost:8888');
// Request methods you wish to allow
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
// Request headers you wish to allow
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
// Set to true if you need the website to include cookies in the requests sent
// to the API (e.g. in case you use sessions)
res.setHeader('Access-Control-Allow-Credentials', true);
// Pass to next layer of middleware
next();
});
两种方法都失败了,我在网上搜索,但每个人的回答都是一样的,现在我对我的服务器发生了什么感到困惑。
如果有人能弄清楚哪里出了问题,我会发布我的 server.js 文件。
const path = require('path');
const http = require('http');
const express = require('express');
const cors = require('cors');
var bodyParser = require('body-parser');
var cookieParser = require('cookie-parser');
const publicPath = path.join(__dirname, '../public');
const port = process.env.PORT || 3000;
var app = express();
app.use(cors())
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(publicPath));
app.listen(port, () => {
console.log(`Server is up on ${port}`);
});
下面提供了错误信息。 XMLHttpRequest 无法加载 https://iot-backend-metropolia.herokuapp.com/api/user .对预检请求的响应未通过访问控制检查:请求的资源上不存在“Access-Control-Allow-Origin” header 。产地' http://localhost:3000 ' 因此不允许访问。
最佳答案
你可以添加这个:
app.all('*', function(req, res, next) {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Headers', 'Content-Type, Content-Length, Authorization, Accept, X-Requested-With , yourHeaderFeild');
res.header('Access-Control-Allow-Methods', 'PUT, POST, GET, DELETE, OPTIONS');
if (req.method == 'OPTIONS') {
res.send(200);
} else {
next();
}
});
关于javascript - Cors 不适用于 XMLhttprequest Node/ express ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42451025/