跨域问题

- 同源策略:协议、域名、端口号三者必须相同,有一个不相同即为跨域

http://localhost:3000

http://127.0.0.1:3000

## 跨域解决方案

1. cors

2. 服务端代理请求

3. jsonp  get  script  src -> res.send('mycallback({a:123,b:456})')

4. 前端本地服务器代理请求

```js

const express = require('express')

const app = express()

// 1.使用cors中间件跨域

const cors = require('cors')

app.use(cors())

// 2.设置头部信息允许跨域

app.all("*",function(req,res,next){

  //设置允许跨域的域名,*代表允许任意域名访问

  res.header("Access-Control-Allow-Origin","*")

  //允许的header类型

  res.header("Access-Control-Allow-Headers","content-type")

  //允许的跨域请求方式 

  res.header("Access-Control-Allow-Methods","POST,GET")

  next()

})

// 3.服务端代理跨域请求

// 可以使用http模块来发起请求,工作中可以使用封装好的request模块

const https = require('https')

app.get('/hehe',(req,response)=>{

  let url = 'https://m.you.163.com/xhr/index.json?__timestamp=1600266481664'

  https.get(url,(res)=>{

    let resData = ''

    // 只要接收到数据就会触发data事件

    res.on('data',(chunk)=>{

      // chunk是每次接收到的数据片段

      resData += chunk.toString('utf8')

    })

    // 数据流传输完毕触发end事件

    res.on('end',()=>{

      response.send(resData)

    })

  })

})

app.listen(3003,()=>{

  console.log('----------- server start ----------');

})

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容