美文网首页
Nodejs Express 跨域访问

Nodejs Express 跨域访问

作者: 远程开发者 | 来源:发表于2021-07-26 22:34 被阅读0次

    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 跨域访问

          本文链接:https://www.haomeiwen.com/subject/piqnmltx.html