写了个elementUI+nodejs+expr ess的页面实现文件上传下载,新建的exp ress项目可以实现浏览器预览但是上传提示跨域,我修改了/bin/www里的代码,现在上传没问题了,但是上传的图片和文档无法通过浏览器地址栏输入路径来访问预览,求大神协助
www代码
#!/usr/bin/env node
/**
* Module dependencies.
*/
var debug = require('debug')('xiaohongfile:server');
var http = require('http');
const exp ress = require("exp ress");
const multer = require("multer");
const fs = require("fs");
const app = new exp ress();
var port = normalizePort(process.env.PORT || '26666');
app.set('port', port);
app.all('*', function (req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "X-Requested-With");
res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
res.header("X-Powered-By", ' 3.2.1');
res.header("Content-Type", "application/json;charset=utf-8");
next();
});
//图片上传
app.post(
"/upload",
multer({
//设置文件存储路径
dest: "public/uploadFile",
}).array("file", 1),
function (req, res, next) {
let files = req.files;
let file = files[0];
let fileInfo = {};
let path = "public/uploadFile/" + Date.now().toString() + "_" + file.originalname;
fs.renameSync("./public/uploadFile/" + file.filename, path);
//获取文件基本信息
fileInfo.type = file.mimetype;
fileInfo.name = file.originalname;
fileInfo.size = file.size;
fileInfo.path = path;
console.log(fileInfo)
let data = {
code: 200,
msg: "OK",
data: fileInfo
}
res.send(data)
});
/**
* Create HTTP server.
*/
var server = http.createServer(app);
/**
* Listen on provided port, on all network interfaces.
*/
server.listen(port);
server.on('error', onError);
server.on('listening', onListening);
/**
* Normalize a port into a number, string, or false.
*/
function normalizePort(val) {
var port = parseInt(val, 10);
if (isNaN(port)) {
// named pipe
return val;
}
if (port >= 0) {
// port number
return port;
}
return false;
}
/**
* Event listener for HTTP server "error" event.
*/
function onError(error) {
if (error.syscall !== 'listen') {
throw error;
}
var bind = typeof port === 'string'
? 'Pipe ' + port
: 'Port ' + port;
// handle specific listen errors with friendly messages
switch (error.code) {
case 'EACCES':
console.error(bind + ' requires elevated privileges');
process.exit(1);
break;
case 'EADDRINUSE':
console.error(bind + ' is already in use');
process.exit(1);
break;
default:
throw error;
}
}
/**
* Event listener for HTTP server "listening" event.
*/
function onListening() {
var addr = server.address();
var bind = typeof addr === 'string'
? 'pipe ' + addr
: 'port ' + addr.port;
debug('Listening on ' + bind);
}