【发布时间】:2017-08-22 10:51:11
【问题描述】:
我已经安装了这个 ng2-file-upload 包,但是我在上传图片时遇到了一些问题,它在控制台中显示了以下错误
OPTIONS http://localhost:3000/api/500(内部服务器错误)
XMLHttpRequest 无法加载 http://localhost:3000/api/。对预检请求的响应未通过访问控制检查:请求的资源上不存在“Access-Control-Allow-Origin”标头。因此,不允许访问 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']
})
【问题讨论】: