Node.js - 在 express 中启用 cors 跨域资源共享

一起养成写作习惯!这是我参与「掘金日新计划 · 4 月更文挑战」的第12天,点击查看活动详情

cors 跨域资源共享

  • 接口的跨域问题

    编写 GET 和 POST 接口,存在一个很严重的问题:不支持跨域请求

  • 示例

    路由模块

    const express = require('express')
    const router = express.Router()
     
    router.post('/post', (req, res) =>{
        const body = req.body
            res.send({
            status:0,
            msg:'POST 请求',
            data:body
        })
    })
    module.exports = router
    复制代码

    服务器端代码

    const express = require('express')
    const app = express()
    
    app.use(express.urlencoded({extended: false}))
    
    const router = require('./apiRouter')
    app.use('/api', router)
    
    app.listen(80, ()=> {
        console.log('express 服务器运行在 http://127.0.0.1.80')
    })
    复制代码

    测试网页

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Document</title>
        <script src="https://cdn.staticfile.org/jquery/1.10.0/jquery.min.js"></script>
    </head>
    <body>
        <button id="postBut"> POST </button>
       
       <script>
        $(function(){
                测试 POST 接口
                $('#postBut').on('click', function(){
                    $.ajax({
                        type:'POST',
                        url:'http://127.0.0.1/api/post',
                        data:{name:'haimeimei', age: 18},
                        success: function(res){
                            console.log(res)
                        }
                    })
                })
            })
        </script>
    </body>
    </html>
    复制代码

    当我们点击网页中 POST 按钮后,请求并没有成功,终端会报错(存在接口跨域问题)。因为网页是通过 file 协议(file:///...)打开的网页,但是请求的接口是 http 协议的,存在协议不同。只要协议、域名、端口号任何一项不同就存在跨域问题

    访问链接:

    Snip20220412_5.png

    终端报错 Snip20220412_3.png


解决接口跨域问题的方案

  • cors 主流的解决方案(推荐使用)
  • jsonp 有缺陷的解决方案(只支持 GET 请求)

使用 cors 中间件解决跨域问题

  • cors 是 Express 的一个第三方中间件,通过安装和配置 cors 中间件,可以很方便地解决跨域问题

  • 使用步骤分为三步

    • 运行 npm install cors 安装中间件
    • 使用 const cors = require('cors') 导入中间件
    • 在路由之前调用 app.use(cors()) 配置中间件
  • 示例

    以上代码不变,只需要更改服务器端代码,一定要在路由之前配置 cors 中间件,从而解决接口跨域问题

     const express = require('express')
     const app = express()
     
     app.use(express.urlencoded({extended: false}))
     
     // 配置 cors 这个中间件
     const cors = require('cors')
     app.use(cors())
     
     const router = require('./apiRouter')
     app.use('/api', router)
     
     app.listen(80, ()=> {
         console.log('express 服务器运行在 http://127.0.0.1.80')
     })
    复制代码

    网页终端信息

    Snip20220412_6.png


猜你喜欢

转载自juejin.im/post/7085641140879228941
今日推荐