Home >Web Front-end >JS Tutorial >How to use JS to achieve the simplest cross-domain

How to use JS to achieve the simplest cross-domain

php中世界最好的语言
php中世界最好的语言Original
2018-06-04 14:25:061633browse

This time I will show you how to use JS to achieve the simplest cross-domain, and what are the precautions for using JS to achieve the simplest cross-domain. The following is a practical case, let's take a look.

One day someone came to me to make a plan and asked me what the principle of cors was. He was confused. I only knew jsonP for cross-domain. I was about to lose an opportunity to show off.
"I'm a little busy now, I'll see you later."
Being smart, I immediately returned to my work station, Baidu Baidu Baidu.

Same origin strategy

It’s a cliché, if you’re not from my family, of course you can’t mess around with things.
Non-original scripts cannot access or operate page objects in other domains (such as DOM, etc.). The same-origin policy requires three same origins, namely: the same domain, the same protocol, and the same port.

Cross-domain method

This article only introduces jsonP and cors.

jsonP

<!-- 开发环境版本,包含了用帮助的命令行警告 --><script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>

This is the method of introducing vue.js into the vue document. You can see that the script tag can directly request JS files from other domains. In this case, we can use this feature to achieve cross-domain.

Build a simple server

Use nodejs express to build a simple server. A few lines of code are enough.

const express = require('express');const app = express();
app.get('/user',(req,res)=>{  console.log('user');
  res.send(‘success’);
})
app.listen(3000,()=>{  console.log('start');
});

Start the server. Then write a test function and try ajax first.

function getUserAjax(){  let xhr= new XMLHttpRequest();
  xhr.open("GET","http://127.0.0.1:3000/user",true);
  xhr.send();
}

Run the getUserAjax function under the chrome console.

How to use JS to achieve the simplest cross-domain

You can see that it was rejected and the browser did not successfully get success. At this time you need to use jsonP. Because the script tag itself can request JS files across domains.

function getUser(){  let dom = document.createElement('script');
  dom.src = "http://127.0.0.1:3000/user";  document.body.appendChild(dom);
}

Run getUser() in the console.

How to use JS to achieve the simplest cross-domain

success is not defined. It can be seen that the browser has obtained ‘success’ across domains. Because the JS loaded by the script tag will be executed immediately, and success is not defined, this error was reported. By this time it was clear. When the front end sends a request, the function name, such as callback, is passed to the backend, and the backend returns this function, callback(info). In this way, after the browser receives the data, it will immediately execute the callback function, just like Callback function. Start modifying immediately:
Front-end code:

function callback(info){
  alert(info);
}function getUser(){  let dom = document.createElement('script');
  dom.src = "http://127.0.0.1:3000/user?callback=callback";  //url上指明回调函数的名字
  document.body.appendChild(dom);
}

Backend code:

const express = require('express');const app = express();
app.get('/user',(req,res)=>{  let func = req.query.callback;
  res.send(func+'(' + '"success"'+')');
});
app.listen(3000,()=>{  console.log('start');
});

Execute getUser(); again and success pops up successfully. This is how jsonP works. The background returns a JS function, takes parameters, and calls the function prepared by the front end. That is, the effect of sending requests and callback functions is achieved.

cors

This is even simpler. This error was reported when the above ajax was cross-domain. No 'Access-Control-Allow-Origin' header is present on the requested resource.
Just bring ''Access-Control-Allow-Origin' when the server returns. What he means is which sources of requests are allowed. Although you are not from my family, I trust you this time and give you a key.
Modify the background code:

const express = require('express');const app = express();
app.get('/user',(req,res)=>{
  res.header("Access-Control-Allow-Origin", "*");  //设置返回数据的头,代表接受任意源的请求
  res.send('success');
});
app.listen(3000,()=>{
  console.log('start');
});

Then call the above getUserAjax() on the console. success. There is no need to change the front-end code. However, it should be noted that not all browsers support cors.

How to use JS to achieve the simplest cross-domain

Comparison between jsonP and cors

cors has the same purpose as jsonP, but is more powerful than jsonP.
jsonP only supports GET requests, cors supports all types of HTTP requests. The advantage of jsonP is that it supports older browsers and can request data from websites that do not support CORS.

I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!

Recommended reading:

Basic data types for js basic improvement learning

How to use JS to customize hash tables and sequential lists

The above is the detailed content of How to use JS to achieve the simplest cross-domain. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn