找了好几个解决跨域的方法,对我的程序都是无效的。前台用代理能解决,但是想试一下纯后台解决跨域,试过下面的,能完美解决。
// 自定义跨域中间件
var allowCors = function(req, res, next) {
res.header('Access-Control-Allow-Origin', req.headers.origin);
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
res.header('Access-Control-Allow-Headers', 'Content-Type');
res.header('Access-Control-Allow-Credentials','true');
next();
};
app.use(allowCors);//使用跨域中间件
app.js 完整代码
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
//用来设置模版引擎
const consolidate=require('consolidate');
var cors = require('cors');
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
/*前后台不分离的话,将ejs模版改为html
app.set('views', 'views');
app.set('view engine', 'html');
app.engine('html',consolidate.ejs);
*/
// app.use(cors({
// "Access-Control-Allow-Origin":'*',
// "Access-Control-Allow-Methods":"DELETE,PUT,POST,GET,OPTIONS",
// "Access-Control-Allow-Credentials": "true"
// }));
// 自定义跨域中间件
var allowCors = function(req, res, next) {
res.header('Access-Control-Allow-Origin', req.headers.origin);
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
res.header('Access-Control-Allow-Headers', 'Content-Type');
res.header('Access-Control-Allow-Credentials','true');
next();
};
app.use(allowCors);//使用跨域中间件
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', indexRouter);
app.use('/users', usersRouter);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
网友评论