祝各位道友念头通达
GitHub Gitee 语雀 打赏

CORS浏览器跨域问题

参考 http://www.ruanyifeng.com/blog/2016/04/cors.html

cors 跨域问题详解

跨域指向的是服务端

  1. 浏览器请求服务器的时候, 当当前ip,端口, 协议类型不同的时候,都会在 Origin 记录并传到服务器

  2. 服务器根据 Origin 来判断是否在 Access-Control-Allow-Origin 允许的范围内

跨域在服务端的响应设置

{
    "Content-Type": "application/json",         // 支持的请求类型
    'Access-Control-Allow-Origin': '*',         //允许所有, 单个 http://localhost:8080/
    "Access-Control-Allow-Methods": "GET",      //跨域支持的请求方法
    "Access-Control-Allow-Headers": "x-requested-with,SESSIONKEY", //头部允许加入的字段, 比如头部字段有SESSIONKEY, 需要在这里加入
    "Access-Control-Allow-Credentials": "true" //否允许发送Cookie
}

跨域中对预检(preflight)的处理 image-20210728155703381

预检的请求方法是 OPTIONS

代码 nodejs

var webconn
const http = require('http')
const urlT = require('url')
function createServer() {
  webconn = http.createServer(function (req, res) {
    /**
     * 1. http://www.ruanyifeng.com/blog/2016/04/cors.html 跨域请求
     * 2. 针对跨域请求中的 preflight 的处理方案, 预检 的请求方法是OPTIONS
     */
    console.log("===========================" + req.url + ", method: " + req.method)
    res.writeHead(200, {
      "Content-Type": "application/json",
      'Access-Control-Allow-Origin': '*',                                   
      "Access-Control-Allow-Methods": "GET",
      "Access-Control-Allow-Headers": "x-requested-with,SESSIONKEY",
      "Access-Control-Allow-Credentials": "true"
    });
    if (req.method !== "OPTIONS") {
      // do something
    }
    res.end()
  }).listen(CONF.SCOKET_PORT, () => { log.info("http 服务器启动成功") })
}
posted @ 2021-07-28 16:04  韩若明瞳  阅读(48)  评论(0编辑  收藏  举报