gpt4 book ai didi

node.js - 在 NodeJS/heroku 中向外部 API 发送 get 请求时出现 CORS 问题

转载 作者:太空宇宙 更新时间:2023-11-03 22:06:52 26 4
gpt4 key购买 nike

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

enter image description here

当我在 Chrome 中打开 CORS 扩展时,它工作得很好。

有人可以告诉我问题是什么吗?

Node 代码

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)
}

最佳答案

您不允许在 Access-Control-Allow-Headers 中使用 Authorization header 。因此添加标题:

更改:

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 ok 状态,因此:

更改您的:

next()

对于:

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

并将其重新部署到 Heroku。

关于node.js - 在 NodeJS/heroku 中向外部 API 发送 get 请求时出现 CORS 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52801753/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com