• ajax跨域请求问题总结


    总结一下近期遇到ajax跨域请求问题

    业务场景描述:

    1. 移动端页面放在阿里云服务器
    2. 进入页面后, 需要访问另一个服务器的接口,ajax请求使用用GET,POST,PUT等方法
    3. 服务端需要进行cors配置

    操作过程中出现的问题

    1. 发送PUT请求时,请求头的method变成OPTIONS, 且浏览器控制台给出提示:Method PUT is not allowed by Access-Control-Allow-Methods in preflight response.

    对于出现OPTIONS请求的理解:
    在跨域请求时,浏览器对于PUT,DELETE等方法,会先发送一次预检请求,该请求头的method就是OPTIONS,服务端需要对这个请求进行处理,浏览器得到服务端支持该请求时,才会发送真正的PUT请求。

    服务器最终配置

    //node跨域配置
    app.all('*', function(req, res, next) {
      let reqOrigin = req.header["origin"];
      if (req.method === 'OPTIONS') {
        console.log(req.method)
        var headers = {};
        // IE8 does not allow domains to be specified, just the *
        // headers["Access-Control-Allow-Origin"] = req.headers.origin;
        headers["Access-Control-Allow-Origin"] = "*";
        headers["Access-Control-Allow-Methods"] = "POST, GET, PUT, DELETE, OPTIONS";
        headers["Access-Control-Allow-Credentials"] = false;
        headers["Access-Control-Allow-Headers"] = "X-Requested-With, X-HTTP-Method-Override, Content-Type, Accept";
        res.writeHead(200, headers);
        res.end();
      } else {
        console.log(req.method)
        res.header("Access-Control-Allow-Origin", "*");
        next()
      }
    });
    
    //or
    
    app.all('*', function(req, res, next) {  
        res.header("Access-Control-Allow-Origin", "*");  
        res.header("Access-Control-Allow-Headers", "X-Requested-With");  
        res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");  
        res.header("X-Powered-By",' 3.2.1')  
        res.header("Content-Type", "application/json;charset=utf-8");  
        next();  
    });
    

    需要注意的一点是,app.all部分的代码需要放置在app.use之前!

    node的cors模块

    问题解决完了发现node提供了解决跨域问题的cors模块。解决跨域问题非常方便,但是由于node服务器只是自己在本地搭建用于测试用,工作中是和java开发配合,所以没有用起来。

    github链接:cors

    示例代码:

    var express = require('express')
    var cors = require('cors')
    var app = express()
    
    app.use(cors())
    
    app.get('/products/:id', function (req, res, next) {
      res.json({msg: 'This is CORS-enabled for all origins!'})
    })
    
    app.listen(80, function () {
      console.log('CORS-enabled web server listening on port 80')
    })
    
  • 相关阅读:
    如何很“礼貌”的避免抛出空指针异常
    如何优雅的使用第三方插件写实体类
    IntelliJ IDEA(2019.03)破解教程(亲测实用)
    vue.js 中使用(...)运算符报错的解决方法
    44个Java性能优化
    Spring MVC原理及配置
    Intellij IDEA 从入门到上瘾 图文教程
    JVM系列二 GC策略&内存申请、对象衰老
    Spring MVC国际化配置
    Java性能优化的50个细节(珍藏版)
  • 原文地址:https://www.cnblogs.com/foxNike/p/7698309.html
Copyright © 2020-2023  润新知