Nodejs Express 跨域访问

app.all('*',function(req,res,next)) -->* 代表所有访问 ,

  res.header('Access-Control-Allow-Origin', '*');  ---->代表同意跨域

  res.header('Access-Control-Allow-Headers', 'Content-Type, Content-Length, Authorization, Accept, X-Requested-With ');  ------>代表支付HTTP头字段

  res.header('Access-Control-Allow-Methods', 'PUT, POST, GET, DELETE, OPTIONS');  ------>代表支持的HTTP方法



//跨域访问

app.all('*',function (req, res, next) {

  res.header('Access-Control-Allow-Origin', '*');

  res.header('Access-Control-Allow-Headers', 'Accept,Content-Type,Content-Length, Authorization,X-Requested-With ');

  res.header('Access-Control-Allow-Methods', 'POST,GET,PUT,DELETE,OPTIONS');

  if ('OPTIONS' == req.method) {

    res.send(200); /让options请求快速返回/

  }

  else {

    next();

  }

});



开户跨域访问,必需放在路由前执行,不然不会生效

app.all('*',function (req, res, next) {

  res.header('Access-Control-Allow-Origin', '*');

  res.header('Access-Control-Allow-Headers', 'Accept,Content-Type,Content-Length, Authorization,X-Requested-With ');

  res.header('Access-Control-Allow-Methods', 'POST,GET,PUT,DELETE,OPTIONS');

  if ('OPTIONS' == req.method) {

    res.send(200); /让options请求快速返回/

  }

  else {

    next();

  }

});

app.use('/', indexRouter);

app.use('/users', usersRouter);

app.use('/admin',adminRouter);

你可能感兴趣的:(Nodejs Express 跨域访问)