跨域是为了解决浏览器请求域名,协议,端口不同的接口,相同的接口是不需要实现跨域的。
1.使用JSONP格式实现跨域
实现步骤
- 动态创建一个script标签
- src指向接口的地址
- 定义一个函数和后端调用的函数名一样
实现代码 -- 在nodejs中使用http内置模块起一个服务,端口号为3000
const url = require('url')
const http = require('http')
const server = http.createServer((req,res)=>{
    if(req.url === '/favicon.ico') return  //图标忽略 --- 图标地址也会请求后台服务
    const {query,pathname} = url.parse(req.url,true)  //若加上true这个参数,query字符串参数会自动转成对象格式
    //设置头部信息 状态为200 内容为JSON格式  如果要返回html片段这设置为text/html
    res.writeHead(200, { 'Content-Type': 'application/json' });
    if(pathname == '/api/data'){
        //定义对象,返回给前端的   数据
        const obj = {code:200,message:'jsonp形式返回给前端'}
        //返回一个JSON调用的函数
        res.end(`toFront(${JSON.stringify(obj)})`)
    }else{
        //简单处理了
        res.writeHead(404, { 'Content-Type': 'application/json' });
        res.end('404')
    }
   //jsonp跨域操作
   //  console.log(req.url) //获取请求除域名外的地址 例如 localhost:300/api  只获取/api
})
server.listen(3000,()=>{
    console.log("服务已启动")
})在客户端的代码
 <script type="text/javascript">
    //jsonp跨域步骤
    //1.动态创建一个script标签
    const newscript = document.createElement('script')
    //2.src指向接口的地址
    newscript.src = 'http://localhost:3000/api/data'
    document.body.appendChild(newscript  )
    //3.定义一个函数和后端调用的函数名一样
    function toFront(res){
      //后台返回的数据  这个函数是后台服务调用过来的
      console.log(res) 
    }
  </script>执行的结果 ,返回一个JSON格式的文档

2.使用cors实现跨域
核心是将响应的数据头部设置一个'access-control-allow-origin':'*',允许所有接口来访问浏览器,把浏览器允许的接口设置开放就好了。若不设置会出现明显的跨域报错问题

下面设置下头部信息
const server = http.createServer((req,res)=>{
    if(req.url === '/favicon.ico') return  //图标忽略 --- 图标地址也会请求后台服务
    const {query,pathname} = url.parse(req.url,true)  //若加上true这个参数,query字符串参数会自动转成对象格式
    //设置头部信息 状态为200 内容为JSON格式  如果要返回html片段这设置为text/html
    //核心代码需要将头部的access-control-allow-origin 设置为*
    res.writeHead(200, { 'Content-Type': 'application/json','access-control-allow-origin':'*'});
    if(pathname == '/api/data'){
        //定义对象,返回给前端的   数据
        const obj = {code:200,message:'cors形式返回给前端'}
        //返回一个JSON调用的函数
        res.end(`${JSON.stringify(obj)}`)
    }else{
        //简单处理了
        res.writeHead(404, { 'Content-Type': 'application/json' });
        res.end('404')
    }
    //jsonp跨域操作
    //  console.log(req.url) //获取请求除域名外的地址 例如 localhost:300/api  只获取/api
})
server.listen(3000,()=>{
    console.log("服务已启动")
})客户端请求
 //cors跨域
    fetch('http://localhost:3000/api/data')
        .then(res=>res.json())
        .then(res=>console.log(res))结果如下





![[Spring] SpringMVC 简介(一)](https://img-blog.csdnimg.cn/b390a6241e1941ff91e73e9edcaf1424.png)













