zoukankan      html  css  js  c++  java
  • node egg 实现跨域

    最近在做node项目,需要提供接口给不同域名的功能使用,于是就产生了跨域问题。下面说一下解决方法:步骤一:# 下载 egg-cors npm i egg-cors --save

    1、安装egg-cors

    npm i egg-cors -S

    2、在config/plugin.js声明

    exports.cors = {
        enable: true,
        package: 'egg-cors',
    };

    3、在config/config.default.js配置

     //跨域配置
    config.security = {
        csrf: {
          enable: false, // 前后端分离,post请求不方便携带_csrf
          ignoreJSON: true
        },
        domainWhiteList: ['http://www.baidu.com', 'http://localhost:8080'], //配置白名单
    };
      
    config.cors = {
        // origin: '*', //允许所有跨域访问,注释掉则允许上面 白名单 访问
        credentials: true, // 允许跨域请求携带cookies
        allowMethods: 'GET,HEAD,PUT,POST,DELETE,PATCH'
    };

    注意,跨域请求时,前端请求打开withCredentials,否则依然无效

    $.ajax({
      url: 'http://www.baidu.com/api/user/getUserInfo',
      xhrFields: {
        withCredentials: true // 携带跨域cookie
      },
      success: function(res) {
        console.log(res);
      }
    });
     
    axios({
      url: 'http://www.baidu.com/api/user/getUserInfo',
      withCredentials: true // 携带跨域cookie
    }).then(res => {
      console.log(res)
    })

    最后注意一点,如果跨域通信,https证书签名要让运维搞好,要不然还是会出现跨域问题。

  • 相关阅读:
    SQL Server逻辑读、预读和物理读
    SQL Server 视图
    SQL Server存储机制
    SQLServer
    数据库配置问题整理贴
    分析存储过程重编译的起因以及避免
    存储过程重编译的优点、缺点、确定引发语句
    查询反模式
    查询反模式
    状压DP的总结
  • 原文地址:https://www.cnblogs.com/wuyuchao/p/13734151.html
Copyright © 2011-2022 走看看