没有'Access-Control-Allow-Origin'反应Express Docker应用

eri*_*n30 5 javascript node.js express docker reactjs

我正在使用docker运行前端React应用程序和节点/表达api。react应用正在运行,localhost:3000而api正在运行localhost:9000。它们都是功能全面且可以正常工作的应用程序。但是,当我尝试从React应用程序拨打电话给http://localhost:9000/api/whatever我时,出现以下错误

XMLHttpRequest cannot load http://localhost:9000/api/schedule. No
Access-Control-Allow-Origin' header is present on the requested 
resource. Origin 'http://localhost:3000' is therefore not allowed access.`
Run Code Online (Sandbox Code Playgroud)

这是我的express api的server.js文件:

const express = require('express');
const port = process.env.PORT || 9000;

const app = express();

require('./app/routes')(app);
app.use(function(req, res, next) {
    // Website you wish to allow to connect
    res.setHeader('Access-Control-Allow-Origin', 'http://localhost:3000');

    // Request methods you wish to allow
    res.setHeader('Access-Control-Allow-Methods', 'GET');

    // 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();
});
app.listen(port, () => {
    console.log('listening on port : ' + port);
})
Run Code Online (Sandbox Code Playgroud)

不知道我在这里想念的是什么。

Chrome网络标签:

Request URL:http://localhost:9000/api/schedule
Request Method:GET
Status Code:200 OK
Remote Address:[::1]:9000
Response Headers
view source
Connection:keep-alive
Content-Length:86
Content-Type:application/json; charset=utf-8
Date:Mon, 10 Apr 2017 04:40:06 GMT
ETag:W/"56-l2wi6AdD2GGTOMvRjRYO96YmR0w"
X-Powered-By:Express
Request Headers
view source
Accept:application/json, text/plain, */*
Accept-Encoding:gzip, deflate, sdch, br
Accept-Language:en-US,en;q=0.8
Connection:keep-alive
Host:localhost:9000
Origin:http://localhost:3000
Referer:http://localhost:3000/
User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36
Run Code Online (Sandbox Code Playgroud)

小智 5

我之前已经能够使用以下配置执行此操作:

app.use((req, res, next) => {
  const origin = req.get('origin');

  // TODO Add origin validation
  res.header('Access-Control-Allow-Origin', origin);
  res.header('Access-Control-Allow-Credentials', true);
  res.header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE');
  res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept, Authorization, Cache-Control, Pragma');

  // intercept OPTIONS method
  if (req.method === 'OPTIONS') {
    res.sendStatus(204);
  } else {
    next();
  }
});
Run Code Online (Sandbox Code Playgroud)

正如你在我的例子中所看到的,我允许更多的方法,而不仅仅是GET一个,并添加了额外的允许头(例如Authorization我在这种情况下需要的头),请注意,在你的情况下,你只指定了X-Requested-Withand Content-Type,但你可能还需要的Origin一个,如果你想验证的来源。

我也在拦截OPTIONS请求以避免在这种情况下发送额外的数据。