CORS对于XMLHttpRequest在Node/Express中不起作用。

6

我知道这个问题看起来像是在重复,但我已经尝试了所有可能的方法使我的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”标头。因此,来自http://localhost:3000的来源不允许访问。

开发工具显示响应头有什么内容? - Daniel T.
@DanielT. 304 没有修改 - Masnad Nihit
1个回答

1
你可以添加这个:
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();
    }
});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接