The creation process of native Ajax == jsonp principle

The creation process of native Ajax

1. Create xhr core object

var xhr=new XMLHttpRequest();

2. Call open to prepare to send
  • Parameter 1: Request method
  • Parameter 2: Request address
  • Parameter three: true asynchronous, false synchronous

xhr.open('post','http://www.baidu.com/api/search',true)

3. If it is a post request, the request header must be set.

xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')

4. Call send to send the request (if parameters are not needed, write null)

xhr.send('user=tom&age=10&sex=女')

5. Monitor the asynchronous callback onreadystatechange
  • Judging that the readyState is 4, the request is complete
  • Judging that the status code is 200, the interface request is successful
  • responeseText is the corresponding data. String type.

  xhr.onreadystatechange=function(){
    
    
          if(xhr.readyState==4){
    
     
            if(xhr.status==200){
    
    
              console.log(xhr.responseText);
              var res=JSON.parse(xhr.responseText);
              console.log(res);
              if(res.code==1){
    
    
                modal.modal('hide');
                location.reload();
              }
            }
          }

Note: If it is a post request, you want to send json format data.

Set request header

xhr.setRequestHeader('Content-Type', 'application/json')

open send data

xhr.open({
    
    _id:xxx,user:xxxx,age:xxxx})

===================================================================

jsonp principle

Preface

The following is a use case of native jsonp. The backend uses a simple server built by node.

1. Front-end code


	<!DOCTYPE html>
	<html lang="en">
	
	<head>
	  <meta charset="UTF-8">
	  <meta name="viewport" content="width=device-width, initial-scale=1.0">
	  <meta http-equiv="X-UA-Compatible" content="ie=edge">
	  <title>Document</title>
	  <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.js"></script>

	</head>
	
	<body>
	  <script>
	    function showInfo123(data) {
    
    
	      console.log(data)
	    }
	  </script>
	
	
	<script src="http://127.0.0.1:3000/getscript?callback=showInfo123"></script>
	<!-- <script>
	  show()
	</script> -->
	
	
	<button id="btn">jsonp</button>
	
	</body>
	
	</html>
	
	<script>
	$('#btn').click(function(){
    
    
	  var frame = document.createElement('script');
	  frame.src = 'http://localhost:3000/getscript?callback=showInfo123';
	  $('body').append(frame);
	})
	</script>

2. Backend code node.js


		  // 导入 http 内置模块
		const http = require('http')
		// 这个核心模块,能够帮我们解析 URL地址,从而拿到  pathname  query 
		const urlModule = require('url')
		
		// 创建一个 http 服务器
		const server = http.createServer()
		// 监听 http 服务器的 request 请求
		server.on('request', function (req, res) {
    
    
		
		  // const url = req.url
		  const {
    
     pathname: url, query } = urlModule.parse(req.url, true)
		
		  if (url === '/getscript') {
    
    
		    // 拼接一个合法的JS脚本,这里拼接的是一个方法的调用
		    // var scriptStr = 'show()'
		
		    var data = {
    
    
		      name: 'xjj',
		      age: 18,
		      gender: '女孩子'
		    }
		
		    var scriptStr = `${
      
      query.callback}(${
      
      JSON.stringify(data)})`
		    // res.end 发送给 客户端, 客户端去把 这个 字符串,当作JS代码去解析执行
		    res.end(scriptStr)
		  } else {
    
    
		    res.end('404')
		  }
		})
		
		// 指定端口号并启动服务器监听
		server.listen(3000, function () {
    
    
		  console.log('server listen at http://127.0.0.1:3000')
		})

Words Summary: Principles of JSONP

Ajax requests are affected by the same-origin policy and cross-domain requests are not allowed. We use the src attribute of the script tag to not be restricted by the same-origin policy. Using this feature jsonp requires the following steps:

1, dynamic creation <script></script>(document.createElement('script'))
2, src attribute set, (src parameters to be included callback=fn) cross-domain request
3, <script></script>added to the page executing (body.appendChild('script'))
4, to define in advance the page callback。
5, the rear end of the callback function returns the execution parameters and wrappedcallback(data)

Remarks:
The server no longer returns the data in JSON format, but returns the callback function package data (fn({name:'tom',age:18})), which is called in src, thus achieving cross-domain.

CORS setup cross-domain request


 //设置允许跨域的域名,*代表允许任意域名跨域  CORS跨域
 res.setHeader("Access-Control-Allow-Origin","http://127.0.0.1:3003");

How to set up proxy cross-domain in vue-cli

In the vue component:

 fn(){
    
    
      this.$axios.get('/api/api/v1/home').then(res=>{
    
    
           console.log(res.data);
      })
    }


module.exports={
    
    
    devServer: {
    
    
        proxy:{
    
    
            '/api':{
    
    
                target:'http://127.0.0.1:3002/',//跨域请求资源地址
                ws:false,//是否启用websockets
    /*开启代理:在本地会创建一个虚拟服务端,然后发送请求的数据,并同时接收请求的数据,
    这样服务端和服务端进行数据的交互就不会有跨域问题*/
                changeOrigin:true
                pathRewrite:{
    
    
                    '^/api':''//注册全局路径
                }
            }
        }
    }
}

Guess you like

Origin blog.csdn.net/WLIULIANBO/article/details/110940029