我已经安装了这个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']
})
答案 0 :(得分:0)
替换它:
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();
});