反向代理中间件:
var proxyMiddleWare = require("http-proxy-middleware");
var proxyPath = "http://mobilecdn.kugou.com"; //目标后端服务地址,被反向代理的第三方api,通过中间件转发实现在自己的项目中跨域访问第三方资源。
var proxyOption = { target: proxyPath, changeOrigin: true };
app.use("/yy", proxyMiddleWare(proxyOptionhash));/yy代表匹配路由,目标地址下匹配到该路由后实行转发
允许跨域访问设置:
app.all('*', function(req, res, next) {//*代表允许所有请求跨域访问
res.header("Access-Control-Allow-Origin", "*")
res.header('Access-Control-Allow-Methods', 'PUT, GET, POST, DELETE, OPTIONS')
res.header("Access-Control-Allow-Headers", "X-Requested-With")
res.header('Access-Control-Allow-Headers', 'Content-Type')
next()
})
访问静态资源文件:
var app = express();
var path = require('path');//路径解析模块
var fs = require('fs');//文件读取模块
app.use(express.static(path.resolve(__dirname, './dist')))
app.get('/', function(req, res) {
const html = fs.readFileSync(path.resolve(__dirname, './dist/index.html'), 'utf-8')
res.send(html)
})
图片上传处理模块:
var formidable = require("formidable");
var form = new formidable.IncomingForm(); //创建上传表单
form.encoding = 'utf-8'; //设置编辑
form.uploadDir = 'public/images/'; //设置上传目录
form.keepExtensions = true; //保留后缀
form.maxFieldsSize = 2 * 1024 * 1024; //文件大小
form.parse(req, function(err, fields, files) {
if (err) {
res.locals.error = err;
res.render('index', { title: TITLE });
return;
}
console.log(files.upimg.name)
var extName = ''; //后缀名
switch (files.upimg.type) {
case 'images/jpeg':
extName = 'jpg';
break;
case 'image/jpeg':
extName = 'jpg';
break;
case 'image/png':
extName = 'png';
break;
case 'image/x-png':
extName = 'png';
break;
// default:
// extName='unknow'
}
if (extName.length == 0) {
res.locals.error = '只支持png和jpg格式图片';
res.render('index', { title: TITLE });
return;
}
// var avatarName = Math.random() + '.' + extName;
//图片写入地址;
var newPath = form.uploadDir + files.upimg.name;
//显示地址;
// var showUrl = domain + '/images/' + avatarName;
console.log("newPath", newPath);
fs.renameSync(files.upimg.path, newPath); //重命名
res.json({
"newPath": newPath
});
});