我的 Node.js API 有问题。我的 API 在端口 3000 上运行,角度前端在端口 4200 上运行。
当我从 Angular 向 API 发送请求时,出现 CORS 错误。我尝试了三种不同的解决方案,但仍然不起作用。
应用程序.use(cors());
Run Code Online (Sandbox Code Playgroud)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(); })
Run Code Online (Sandbox Code Playgroud)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);
Run Code Online (Sandbox Code Playgroud)
错误信息:
对其他来源的资源的请求已被阻止:“同源策略”策略不允许从“ 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
}));
Run Code Online (Sandbox Code Playgroud)
您也可以尝试使用等allowedHeaders。exposedHeaders设置maxAge将减少飞行前请求的数量 - 它并不能真正解决 cors 问题,但会减少网络流量。
注意
origin: true. 如果您的端点需要凭据,那么浏览器将不会遵循该*模式。Access-Control-Allow-Origin 标头必须与请求的 url 匹配(包括是否为 http 或 https)。幸运的是,cors如果您设置为,中间件会自动为您执行此origin操作true
| 归档时间: |
|
| 查看次数: |
4313 次 |
| 最近记录: |