簡體   English   中英

ng2-file-upload 500內部服務器問題

[英]ng2-file-upload 500 internal server issue

我已經安裝了此ng2-file-upload軟件包,但在上傳圖片時遇到了一些問題,它向我顯示了控制台中的以下錯誤

選項http:// localhost:3000 / api / 500(內部服務器錯誤)

XMLHttpRequest無法加載http:// localhost:3000 / api / 對預檢請求的響應未通過訪問控制檢查:請求的資源上不存在“ Access-Control-Allow-Origin”標頭。 因此,不允許訪問源' 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']
})

替換為:

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();
  });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM