nodejs+express4如何设置跨域访问
阅读(526)
2017-12-03
由于某些时候需要用nodejs来提供一些接口。在浏览器安全性问题上是禁止跨域访问的。那nodejs+express4如何设置跨域访问呢?下面我们来看下:
我的环境:
win10
nodejs 8.1.2
express 4.15.2
设置跨域:
跨域访问设置,在 app.js 文件的 var app = express(); 这句代码后面加入以下代码即可
var app = express(); 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","POST,GET");//PUT,POST,GET,DELETE,OPTIONS res.header("X-Powered-By",'weizhixi.com 1.0.0');//Your Powered By next(); });
完整示例:
app.js
var express = require('express'); var path = require('path'); var favicon = require('serve-favicon'); var logger = require('morgan'); var cookieParser = require('cookie-parser'); var bodyParser = require('body-parser'); var index = require('./routes/index'); var users = require('./routes/users'); var app = express(); 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","POST,GET");//PUT,POST,GET,DELETE,OPTIONS res.header("X-Powered-By",'weizhixi.com 1.0.0');//Your Powered By next(); }); // view engine setup app.set('views', path.join(__dirname, 'views')); app.set('view engine', 'ejs'); // uncomment after placing your favicon in /public //app.use(favicon(path.join(__dirname, 'public', 'favicon.ico'))); app.use(logger('dev')); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: false })); app.use(cookieParser()); app.use(express.static(path.join(__dirname, 'public'))); app.use('/', index); app.use('/users', users); // catch 404 and forward to error handler app.use(function(req, res, next) { var err = new Error('Not Found'); err.status = 404; next(err); }); // 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;
已下载:93 次
原创文章,转载请注明出处:https://www.weizhixi.com/article/15.html