zoukankan      html  css  js  c++  java
  • express后端配置,实现跨域

    方法1:直接在app.js输入

    //解决跨域
    app.use((req, res, next) => {
      // 设置是否运行客户端设置 withCredentials
      // 即在不同域名下发出的请求也可以携带 cookie
      res.header("Access-Control-Allow-Credentials",true)
      // 第二个参数表示允许跨域的域名,* 代表所有域名  
      res.header('Access-Control-Allow-Origin', 'http://localhost')//配置80端口跨域
      res.header('Access-Control-Allow-Methods', 'GET, PUT, POST, OPTIONS') // 允许的 http 请求的方法
      // 允许前台获得的除 Cache-Control、Content-Language、Content-Type、Expires、Last-Modified、Pragma 这几张基本响应头之外的响应头
      res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization, Content-Length, X-Requested-With')
      if (req.method == 'OPTIONS') {
          res.sendStatus(200)
      } else {
          next()
      }
    })

    方法2:使用中间件cros

    (1)先npm install cros --save

    (2)在app.js输入

    const cors = require('cors')
    app.use(cors({
      origin: ['http://localhost:80'], //前端地址
      methods: ['GET', 'POST'],
      alloweHeaders: ['Conten-Type', 'Authorization'],
      Credentials:['true']
    }))

     若是使用vue,也可以前端配置跨域,可以看看我的另一篇:vue前端配置跨域

    穷则独善其身,达则兼济天下……
  • 相关阅读:
    LoadRunner创建脚本和场景流程
    Monitorix系统和网络监控工具
    查询日志logcat使用总结
    SqlServer存储过程示例
    编写sql查询语句思路
    dstat工具使用介绍
    dstat参数选项
    SqlServer50条常用查询语句
    MySQL查询示例
    CMake 常用方法
  • 原文地址:https://www.cnblogs.com/hmy-666/p/14727220.html
Copyright © 2011-2022 走看看