node.js - CORS 阻止我将图像/文件发送到我的后端
问题描述
我有点沮丧,因为我有以下 CORS 错误,我现在正在处理它大约 4 个小时:
Access to XMLHttpRequest at 'http://localhost:8080/create-post/1' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.
---
POST http://localhost:8080/create-post/1 net::ERR_FAILED
我找不到问题的答案。我在 Angular 中的服务:
服务.ts
...
uploadPicture(file) {
return this.httpClient.post("http://localhost:8080/create-post/1", file)
.pipe(catchError(this.handleError));
}
我的组件
...
onFileChanged(e) {
const file = e.target.files[0];
console.log(file)
this._service.uploadPicture(e.target.files[0]).subscribe((test)=>{
console.log(test)
})
}
我的后台
...
app.use(function (req, res, next) {
res.header("Access-Control-Allow-Origin", '*');
res.header('Access-Control-Allow-Methods: GET, POST, PATCH, PUT, DELETE, OPTIONS');
res.header('Access-Control-Allow-Headers: Origin, Content-Type, X-Auth-Token');
res.header("Access-Control-Allow-Headers", "X-Requested-With, Content-Type");
next();
});
...
app.post('/create-post/:id', function (req, res) {
res.setHeader('Content-Type', 'image/png');
console.log("test")
fs.writeFile("/tmp/test.jpg", req.body.bild, 'binary', function(err) {
if(err)
console.log(err);
else
console.log("The file was saved!");
return res.send('WORK PLEASE')
});
});
它甚至没有触发console.log("test")
POST 方法中的行,所以它在到达那里之前就已经失败了。
感谢您的每一个回答!
解决方案
比你手动设置它。你最好使用cors库。
用法:
var express = require('express')
var cors = require('cors')
var app = express()
app.use(cors()) //Add CORS middleware
app.post('/create-post/:id', function (req, res) {
res.setHeader('Content-Type', 'image/png');
console.log("test")
fs.writeFile("/tmp/test.jpg", req.body.bild, 'binary', function(err) {
if(err)
console.log(err);
else
console.log("The file was saved!");
return res.send('WORK PLEASE')
});
});
推荐阅读
- ios - iOS 谷歌地图标记,带有箭头的圆形气泡内的照片
- php - 从过滤器类别中删除“全部”并设置另一个 jquery
- javascript - 数据表滚动条有时会消失
- python - 如何使用python将一系列HSV值的所有像素设置为openCV中的另一个值?
- ruby-on-rails - redirect_to new_user_session_path 不显示 Flash 消息
- javascript - 离子验证突出显示不适用于离子选择
- android - 删除部分 ImageSpan 时删除整个 ImageSpan
- ssl - TLS 记录协议如何重组接收到的数据?
- r - 在 bookdown 的 pdf_book before_body 中运行 knitr 代码块
- java - Eclipse 光子丢失 java 文件