提问者:小点点

ng2-文件-上传500内部服务器问题


我已经安装了这个ng2文件上传包,但是我在上传图片时遇到了一些问题,它在控制台上显示了以下错误

选项http://localhost:3000/api/500(内部服务器错误)

XMLHttpRequest 无法加载 http://localhost:3000/api/。对预检请求的响应未通过访问控制检查:请求的资源上不存在“访问控制允许源”标头。因此,不允许访问源“http://localhost:4200”。响应具有 HTTP 状态代码 500。

我的api server.js文件代码是

var express = require('express');
var multer = require('multer');
var fs = require('fs');
var app = express();

var DIR = './uploads/';

var upload = multer({dest: DIR});

app.use(function (req, res, next) {
 res.setHeader("Access-Control-Allow-Methods", 
    "POST, PUT, OPTIONS,   DELETE, GET");
    header('Access-Control-Allow-Origin: http://localhost:4200');

    header('Access-Control-Allow-Methods: GET, POST, PATCH, 
    PUT, DELETE, OPTIONS');

    header('Access-Control-Allow-Headers: Origin, Content-Type');
    next();
});


 app.get('/api', function (req, res) {
  res.end('file catcher example');
 });

app.post('/api', function (req, res) {
 upload(req, res, function (err) {
    if (err) {
      return res.end(err.toString());
    }
    res.end('File is uploaded');
   });
});

var PORT = process.env.PORT || 3000;

app.listen(PORT, function () {
 console.log('Working on port ' + PORT);
});

AdminComponent.ts 代码

 import { FileSelectDirective, FileDropDirective, FileUploader, 
 Headers  } from 'ng2-file-upload/ng2-file-upload';

 const URL = 'http://localhost:3000/api/';

@Component({
  selector  : 'app-admin',
  templateUrl   : './admin.component.html',
  styleUrls : ['./admin.component.css']
})

共1个答案

匿名用户

替换此内容:

app.use(function (req, res, next) {
 res.setHeader("Access-Control-Allow-Methods", 
    "POST, PUT, OPTIONS,   DELETE, GET");
    header('Access-Control-Allow-Origin: http://localhost:4200');

    header('Access-Control-Allow-Methods: GET, POST, PATCH, 
    PUT, DELETE, OPTIONS');

    header('Access-Control-Allow-Headers: Origin, Content-Type');
    next();
});

app.use(function(req, res, next) {
    res.header("Access-Control-Allow-Origin", 'http://localhost:4200');
    res.header("Access-Control-Allow-Credentials", true);
    res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
    res.header("Access-Control-Allow-Headers", 'Origin,X-Requested-With,Content-Type,Accept,content-type,application/json');
    next();
  });