node.js - 带有Angular的Node.js - 我发送请求时出现CORS错误
问题描述
我的 node.js API 有问题。我在端口 3000 上运行 API,在端口 4200 上运行角度前端。
当我从 Angular 向 API 发送请求时,CORS 出现错误。我尝试了三种不同的解决方案,但仍然无法正常工作。
- 第一个解决方案是安装 cors 包,并添加到代码中
app.use(cors());
- 第二种解决方案是在下面添加代码:
app.use((req, res, next) => { res.header("Access-Control-Allow-Origin", "*"); res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept"); res.header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS"); next(); })
- 最后一个解决方案是在下面添加代码,带有前端 url:
app.use(cors({ origin: 'http://frontend.com:4200' }));
以上都不起作用,即我仍然一直收到 CORS 错误。当我从邮递员发送请求时,一切正常。
我的实际代码:
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
const carRoutes = require('./routes/car');
const sequelize = require('./util/db');
const cors = require('cors');
sequelize.sync().catch(error => {
console.log(error);
});
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(cors());
app.use(carRoutes);
app.listen(3001);
错误信息:
对另一个来源的资源的请求已被阻止:“同源策略”策略不允许从“ http://localhost:3000/car ”加载远程资源(CORS 请求失败)。
解决方案
有时 CORS 不仅仅是 Access-Control-Allow-Origin。尝试以下操作:
// Set up CORS
app.use(cors({
origin: true, // "true" will copy the domain of the request back
// to the reply. If you need more control than this
// use a function.
credentials: true, // This MUST be "true" if your endpoint is
// authenticated via either a session cookie
// or Authorization header. Otherwise the
// browser will block the response.
methods: 'POST,GET,PUT,OPTIONS,DELETE' // Make sure you're not blocking
// pre-flight OPTIONS requests
}));
您也可以使用allowedHeaders
等exposedHeaders
。设置maxAge
将减少飞行前请求的数量 - 它并不能真正解决 cors 问题,但会减少网络流量。
请注意
origin: true
。如果您的端点需要凭据,则浏览器将不遵守该*
模式。Access-Control-Allow-Origin 标头必须与请求的 url 匹配(包括天气是 http 或 https)。幸运的是cors
,如果您设置origin
为,中间件会自动为您执行此操作true
推荐阅读
- r - 在R中的flextable包中将数字列格式化为百分比
- wordpress - Wordpress Gutenberg 自定义列块
- python - 返回 PubSub 回调消息
- sphinx - Sphinx(搜索引擎)3 不读取 CSV 文件
- c++ - 我可以在稍后声明的名称空间中定义名称吗?
- api - 将值传递给 api 以返回所有值
- git - git ls-files:仅显示 blob 文件
- snowflake-cloud-data-platform - 雪花任务和流 - 复杂性和可视化
- r - 在小标题的整行中搜索字符串?
- typescript - 升级的 Typescript - 尝试导入错误:“BaseMap”未从“./core”导出。- 这是