node.js - 即使在服务器代码中添加标头后,跨域请求也被阻止
问题描述
我在 Express/Node 中有一个简单的 API,还有一个用于发布博客的简单 Angular 应用程序。唯一的问题是当我/contribute
使用 POST 方法到达路线时。我在 chrome 和 firefox 上都遇到了这个错误:
error: error { target: XMLHttpRequest, isTrusted: true, lengthComputable: false, ... } headers: Object { normalizedNames: Map(0), lazyUpdate: null, headers: Map(0) } message: “本地主机的 Http 失败响应:3000/api/contribute: 0 Unknown Error" name: "HttpErrorResponse" ok: false status: 0 statusText: "Unknown Error" url: "localhost:3000/api/contribute" : {…} 构造函数:类 HttpErrorResponse { 构造函数(init) }:{…} 构造函数:类 HttpResponseBase { 构造函数(init,defaultStatus,defaultStatusText)}:{…</p>
这是我的服务器端代码。
api.js
...
router.post('/contribute', (req, res) => {
console.log('Pushing new article');
let userPost = req.body;
let post = new Post(userPost);
post.save((error, registeredPost) => {
if (error) {
console.log(error);
} else {
res.status(200).send(registeredPost);
}
})
})
...
module.exports = router;
服务器.js
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
const api = require('./routes/api');
const cors = require('cors');
app.use(bodyParser.json());
// app.use(cors({ origin: 'http://localhost:4200' })); <--- TRIED THIS ALSO
app.use(function (req, res, next) {
// Website you wish to allow to connect
res.setHeader('Access-Control-Allow-Origin', 'http://localhost:4200');
// Request methods you wish to allow
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
// Request headers you wish to allow
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
// Set to true if you need the website to include cookies in the requests sent
// to the API (e.g. in case you use sessions)
res.setHeader('Access-Control-Allow-Credentials', true);
// Pass to next layer of middleware
next();
});
app.use('/api', api);
app.get('/', function(req, res) {
res.send('Server is up and running!');
})
app.listen(3000, function() {
console.log('Server listening port:3000');
});
是的,服务器已启动并正在运行。
这是角度代码。 auth.service.ts
private _contributeUrl = "https://localhost:3000/api/contribute";
...
pushNewPost(newPost) {
console.log("here is the new post", newPost); // GETTING CORRECT OUTPUT
return this._http.post<any>(this._contributeUrl, newPost);
}
贡献.component.ts
this._auth.pushNewPost(this.makeNewPost)
.subscribe (
res => {
(<HTMLInputElement>document.getElementById("inputTitle")).value="";
this.editorForm.reset();
this.addSingle();
},
err => console.log(err)
);
现在有趣的部分是,当我使用 Postman 向这条路线发出发布请求时,相同的代码可以完美运行,没有任何错误。
请纠正我的错误。添加后:
pushNewPost(newPost) {
console.log("here is the new post", newPost);
let headers = new HttpHeaders({
'Content-Type': 'application/json',
});
let options = { headers: headers };
return this._http.post<any>(this._contributeUrl, newPost);
}
我得到这个:
解决方案
好像您没有从角度发送标题。进行以下更改:
pushNewPost(newPost) {
// adding the headers
const headers = new HttpHeaders({
'Content-Type': 'application/json',
});
const options = { headers: headers };
return this._http.post<any>(this._contributeUrl, newPost, options);
}
推荐阅读
- python - 在浮点上使用 f 字符串格式打印 - 无法获得输出的生成方式
- scala - 在带有 Source.queue 和 Sink.queue 的 akka 流媒体程序中,我提供了 1000 个项目,但是当我尝试将它们取出时它只是挂起
- c# - Unity 中的 Facebook 横幅广告问题
- python-2.7 - 如何为 python 2.7 安装 wily 工具?
- java - 类中的构造函数不能应用于给定类型;发现:java.lang.String,char 原因:实际参数列表和形式参数列表的长度不同
- unity3d - 在 Unity 中使用任何“LightMode”标签时,着色器变为洋红色或不可见
- c# - 在MVC c#中准备自定义json格式返回
- pandas - 从多列级别选择数据
- python - Word2Vec 词汇相似之处
- python - NLTK 话语树到边缘列表