• 【Node.js】暴露自定义响应头和预检请求的时机


    1. 暴露自定义响应头

    // server.js
    app.post('/api/user/hello', (req, res) => {
       res.setHeader('Access-Control-Allow-Origin', '*')
       // 权限设置(如果有个多,用 ,隔开),暴露给前端
       res.setHeader('Access-Control-expose-Headers', 'myHeader')
       // 后端自定义响应头
       res.set('myHeader', 123)
       res.json({ hello: 'world' })
    })
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    // index.html
    fetch('http://localhost:3000/api/user/hello', {
       method: 'POST',
       headers: {
          'Content-Type': 'application/json'
       }
    }).then(res => {
       // 前端获取自定义响应头(前提:后端需要加一个权限)
       console.log(res.headers.get('myHeader'))
       return res.json()
    }).then(response => {
    
    })
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    预检请求(options)的时机

    需要满足以下条件

    1. 'Content-Type''application/json'
    2. 非普通请求:patch,put,delete等
    3. 或者是自定义响应头
    fetch('http://localhost:3000/list', {
            method: 'POST',
            headers:{
                'Content-Type':'application/json'
            },
            body: JSON.stringify({"name": "add"})
        })
        .then(res=> {
            res.json()
        })
        .then(data=>{
            console.log(data)
        })
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    在这里插入图片描述
    在这里插入图片描述

    app.use('*', (req, res, next) => {
        //此时后端为 localhost:3000 如果设为 * 则都可以请求,但是不能种 session
        //Access-Control-Allow-Origin 默认只支持 get post head
        res.setHeader('Access-Control-Allow-Origin', 'http://127.0.0.1:3000')
        res.setHeader('Access-Control-Allow-Methods', 'GET,POST,HEAD,PATCH,DELETE,PUT')
        //支持application/json
        res.setHeader('Access-Control-Allow-Headers', 'Content-Type')
        next()
    })
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
  • 相关阅读:
    你用过哪些设计模式(一)?
    使用easyexcel导出\入excel
    【CEOI2022】Drawing(全局平衡二叉树,构造,分治)
    PHP基础与安全
    面试突击:说一下 Spring 事务传播机制?
    41. Linux系统配置FTP服务器并在QT中使用QFtp实现文件上传
    brew 安装MySQL 5.7
    windows 安装 MySQL 绿色版
    基于springboot的药品管理
    styleSwin的各种bug
  • 原文地址:https://blog.csdn.net/XiugongHao/article/details/134012767