我使用express.static内置中间件函数来提供静态文件,但控制台会输出错误:发送后无法设置标题。
这是我的代码,我不知道这个
有什么问题'use strict';
let path = require('path');
let express = require('express');
let bodyParser = require('body-parser');
let mongoose = require('mongoose');
let formidable = require('express-formidable');
let routes = require('./routes');
let app = express();
let port = process.env.PORT || 3000;
let db = mongoose.connect('mongodb://localhost:27017/old-driver');
// deal with img post
app.use(formidable({
uploadDir: path.join(__dirname, 'upload'),
keepExtensions: true
}));
app.use(bodyParser.urlencoded({extended: true }));
app.use(bodyParser.json());
// access-control
app.all('*', (req, res, next) => {
res.set("Access-Control-Allow-Origin", "*");
res.set("Access-Control-Allow-Headers", "Content-Type,X-Requested-With");
res.set("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
res.set("X-Powered-By",' 3.2.1')
res.type("application/json");
res.type("jpg");
next();
});
// set assets path, GET /assets/demo.png
app.use('/assets', express.static('upload'));
routes(app);
app.listen(port);
路由中间件方法:
getAllTeachers: (req, res) => {
Teacher.find({}, (err, teacher) => {
if (err) {
res.send(err);
} else {
res.json(teacher);
}
});
},
即使我删除了如下所示的access-contol代码,仍会出现错误
let db = mongoose.connect('mongodb://localhost:27017/old-driver');
// deal with img post
app.use(formidable({
uploadDir: path.join(__dirname, 'upload'),
keepExtensions: true
}));
app.use(bodyParser.urlencoded({extended: true }));
app.use(bodyParser.json());
// set assets path, GET /assets/demo.png
app.use('/assets', express.static('upload'));
routes(app);
app.listen(port);
当我请求2个现有的jpg文件时,我在一个jpg文件中也得到404错误 404 screenshot
答案 0 :(得分:3)
要解决此问题,您需要使用app.use
函数而不是app.all
来安装中间件功能。 app.use
将中间件功能添加到中间件堆栈,确保它们按照添加它们的顺序执行。
所以你需要这样做:
app.use((req, res, next) => { //change app.all to app.use here and remove '*', i.e. the first parameter part
res.set("Access-Control-Allow-Origin", "*");
res.set("Access-Control-Allow-Headers", "Content-Type,X-Requested-With");
res.set("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
res.set("X-Powered-By",' 3.2.1')
res.type("application/json");
res.type("jpg");
next();
});
修改强>
正如您在评论中所说,上述方法不起作用,因此您可以使用express.static
方法的setHeaders方法在文件提供之前设置标题,如下所示:
app.use('/assets', express.static('upload', {
setHeaders: function(res, path) {
res.set("Access-Control-Allow-Origin", "*");
res.set("Access-Control-Allow-Headers", "Content-Type,X-Requested-With");
res.set("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
res.set("X-Powered-By",' 3.2.1')
res.type("application/json");
res.type("jpg");
}
}));
将此静态文件服务于中间件方法 高于app.use
,以便不调用用于设置标头的app.use方法,因此不会再次设置标头。