【发布时间】:2017-07-16 00:23:55
【问题描述】:
我知道这感觉像是一个重复的问题,但我已经尝试了所有可能的方式来让我的 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”标头。 Origin 'http://localhost:3000' 因此不允许访问。
【问题讨论】:
-
devtools 对响应头显示什么?
-
@DanielT。 304 未修改
标签: javascript ajax node.js express xmlhttprequest