CORS

CORS是一个W3C标准,全称是"跨域资源共享"(Cross-origin resource sharing)。它允许浏览器向跨源服务器,发出XMLHttpRequest请求,从而克服了AJAX只能同源使用的限制。CORS需要浏览器和服务器同时支持。目前,所有主流浏览器都支持该功能IE10以下不支持。

Express中通过第3方中间件来完成cors跨域解决

使用步骤分为如下 3 步:

① 运行 npm install cors 安装中间件

② 使用 const cors = require('cors') 导入中间件

③ 在路由之前调用 app.use(cors()) 配置中间件

安装cors模块

在中间件中注册

const express = require('express')
const cors = require('cors')
// 实例化一个对象
const app = express()
// 监听服务
app.listen(9000)
// 只有在此数据中的域名才能跨域
const allowHosts = [
    'http://localhost:5500',
    'http://localhost'
]
// 跨域设置
app.use(cors())
app.use((req, res, next) => {
    let host = req.headers.origin
    if (allowHosts.includes(host)) {
        next()
    } else {
        return res.send({
            code: 1000,
            msg:'就是不给'
        })
    }
})
// 定义路由
app.use('/v1',require('./routers/v1'))

在客户端中使用xhr发起网络请求得到数据

let url = 'http://localhost:3000/v1/web'
const xhr = new XMLHttpRequest()
xhr.onreadystatechange = () => {
    if (xhr.readyState === 4 && xhr.ststus === 200) {
         console.log(JSON.parse(xhr.responseText))
     }
}
xhr.get('GET', url, true)
xhr.send(null)

 

右侧打赏一下 代码改变世界一块二块也是爱
原文地址:https://www.cnblogs.com/ht955/p/14283516.html