在将获取请求发送到外部API中时,CORS出现问题-NodeJS / heroku

时间:2018-10-14 10:32:33

标签: node.js heroku

我有一个使用heroku服务器在“ Angular / NodeJs”中构建的应用程序。 在应用程序中,我可以选择在“ omdbapi”中搜索电影。一切正常,直到我执行搜索,控制台都会出现下一个错误:

enter image description here

当我打开Chrome中的CORS扩展程序时,效果很好。

有人可以建议我是什么问题。

节点代码

const express      = require('express');
const bodyParser   = require('body-parser');
const mongoose     = require('mongoose');
const app          = express();
const path         = require('path');
const compression  = require('compression');
const port         = process.env.PORT || 8000;
const cors         = require('cors')

app.use(function(req, res, next) {
    res.header("Access-Control-Allow-Origin", '*');
    res.header("Access-Control-Allow-Credentials", true);
    res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
    res.header("Access-Control-Allow-Headers", 'Origin,X-Requested-With,Content-Type,Accept,content-type,application/json');
    next();
});

app.use(compression());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use("/images", express.static(path.join(__dirname, "images")));
app.use("/", express.static(path.join(__dirname, "angular")));

app.use((req, res, next) => {
    res.sendFile(path.join(__dirname, "angular", "index.html"));
});


app.listen(port, () => {
    console.log("App is running on port " + port);

[编辑] 将标头更改为@jbarros建议后,点仍然起作用。

const express      = require('express');
const bodyParser   = require('body-parser');
const mongoose     = require('mongoose');
const app          = express();
const path         = require('path');
const compression  = require('compression');
const port         = process.env.PORT || 8000;

app.use(function(req, res, next) {
    res.header("Access-Control-Allow-Origin", '*');
    res.header("Access-Control-Allow-Credentials", true);
    res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
    res.header("Access-Control-Allow-Headers", 'Authorization, Origin,X-Requested-With,Content-Type,Accept,content-type,application/json');
    next();
});

角度获取功能

  getMoviesByName(movieName: string) {
    const url = 'https://www.omdbapi.com/?s=' + movieName + '&apikey=xxxxxxx&type=movie'
    return this.http.get<{Search: ImportedMovieModal[]}>(url)
  }

1 个答案:

答案 0 :(得分:2)

您不允许Authorization中的Access-Control-Allow-Headers标头。 因此添加标题:

更改:

res.header("Access-Control-Allow-Headers", 'Origin,X-Requested-With,Content-Type,Accept,content-type,application/json');

针对:

res.header("Access-Control-Allow-Headers", 'Authorization, Origin,X-Requested-With,Content-Type,Accept,content-type,application/json');

此外,您可能需要拦截OPTIONS方法以发送HTTP正常状态,因此:

更改您的:

next()

针对:

// intercept OPTIONS method
if ('OPTIONS' == req.method) {
    res.send(200);
} else {
    next();
}

然后将其重新部署到Heroku。