jsonp 解决跨域

  • 创建index.html,因为<script>、<img>、<iframe>、<link>标签不受同源策略的限制,所以通过生成 script 标签,然后给标签的 src 属性设置为请求接口地址的方法来请求数据
    • 但是由于浏览器 CORB 策略,必须通过请求接口的回调函数获取到数据,因此需要在请求地址后加上后台规定的 jsonp 请求参数名和前端定义的回调函数名,并且前端写一个同名函数,函数参数即为请求的响应数据
    • ?jsonpCallback(后台规定)= callback(前端自定义)
  • 创建server.js,使用node.js写一个简单的接口,运行服务
    • 如果请求中带有请求jsonp的回调函数名则返回jsonp数据,没有则返回 json 数据
  • 创建 client.js,使用node.js开启一个本地服务器,运行 index.html

代码

server.js

const http = require('http');
const querystring = require('querystring')
const PORT = 8000;

http.createServer((req, res) => {
    
    
  const url = req.url;
  console.log('request url: ', url);
  const pathname = url.split("?")[0]
  const query = querystring.parse(req.url.split("?")[1])
  if (pathname === '/api/data') {
    
    
    let result = {
    
    
      code:200,
      msg:"ok",
      data:{
    
    
          name:"mie",
          age:"12"
      }
    }
    result = JSON.stringify(result)
    if(query && query.jsonpCallback){
    
    
      const cbName = query.jsonpCallback
      return res.end(`${
      
      cbName}(${
      
      result})`)
    }else{
    
    
      return res.end(result);
    }
  }
}).listen(PORT);

console.log('Server listening on port '+PORT);

index.html

<!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>index.html</title>
</head>
<body>
    
    <h3>test jsonp</h1>
    <script>
        let url = "http://127.0.0.1:8000/api/data"
        let script = document.createElement("script")
        script.src = url
        document.body.appendChild(script)
    </script>
</body>
</html>

client.js

const http = require("http")
const fs = require('fs');
http.createServer((req, res) => {
    
    
  fs.createReadStream('index.html').pipe(res);
}).listen(3000);
console.log("running at 127.0.0.1:3000")

猜你喜欢

转载自blog.csdn.net/qq_39706777/article/details/120918952