node.js-CORS问题:无法使用NodeJs和Angular发送post请求
发布时间:2022-05-01 17:33:23 235
相关标签: # html5# node.js
我在尝试发送post请求时收到以下消息:
Access to XMLHttpRequest at 'http://localhost:3002/api/products/checkout' from origin
'http://localhost:4200' has been blocked by CORS policy: Request header field content-type
is not allowed by Access-Control-Allow-Headers in preflight response.
现在,我只是尝试将数据发送到后端,然后将其登录到控制台。Get请求工作正常,但由于某种原因,我在尝试发布时遇到了CORS错误。这是我的代码:
角度代码:
//api call
return this.http.post('http://localhost:3000/api/checkout', cart)
NodeJs代码:
const bodyParser = require('body-parser');
const express = require('express');
const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use((req, res, next) => {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader(
'Access-Control-Allow-Header',
'Origin, X-Requested-With, Content-Type, Accept');
res.setHeader(
'Access-Control-Allow-Methods',
'GET, POST, PATCH, DELETE, OPTIONS');
next();
})
app.post("/api/checkout", (req, res, next) => {
const cart = req.body;
console.log(cart)
res.status(201).json()
})
module.exports = app;
特别声明:以上内容(图片及文字)均为互联网收集或者用户上传发布,本站仅提供信息存储服务!如有侵权或有涉及法律问题请联系我们。
举报