首页 > 解决方案 > 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 方法中的行,所以它在到达那里之前就已经失败了。

感谢您的每一个回答!

标签: node.jsangularcorsbackend

解决方案


比你手动设置它。你最好使用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')
  });
});

推荐阅读