1, the cross-domain issues
(1) What is the cross-domain problem?
What is a domain? A domain by the protocol, domain names, together constitute the three ports
What is cross-domain? As long as the protocol, domain names, any one of three different port, as it is across domains
What is cross-domain problem? Simply put, the browser does not allow cross-domain requests resources
(2) Why is cross-domain problem?
Why is cross-domain problem? This is because the browser same origin policy restrictions
What is the origin policy? How same-origin policy to limit a source document or script loaded interact with resources from another source
Why have the same origin policy? It is an important security mechanism for isolating potentially malicious files
(3) why cross-domain requests?
If we talk about cross-domain requests be a security problem, then why do we have cross-domain request it?
This is also a way to get Mo Yeah, sometimes the same company will have a number of different sub-domains, you need to request resources with each other
2, cross-domain solutions to problems
(0) Prepare the environment
Let's take a simple test environment to build a whole file structure is as follows:
+ back_end
+ node_modules
- package-lock.json
- package.json
- server.js
+ front_end
+ node_modules
- index.vue
- package-lock.json
- package.json
① rear end portion [Node.js + Express]
In the back_end
run directory npm init
command to create package.json
a file
Then use the npm install --save express
command to install express
Then create a named server.js
file, enter the following in the file:
// 引入 express 模块
const express = require('express')
// 创建 express 实例
var app = express()
// 设置路由
app.get('/api', function(req, res) {
// console.log(req.query.message)
res.json({
'message': req.query.message
})
})
app.get('/', function(req, res) {
res.send('Hello World')
})
// 启动服务器,监听端口 5000
var server = app.listen(5000)
Run command line node server.js
to start express server 127.0.0.1:5000
( )
② distal portion] [Vue + jQuery
Also in the front_end
running directory npm init
commands, create package.json
documents
Then use the npm install --save jquery
command to install jquery
Use npm install -g @vue/cli
the command to install the global Vue
Use npm install -g @vue/cli-service-global
the command to install a global expansion
Then create a named index.vue
file, enter the following in the file:
<template>
<div>
<input class="enter-message" v-model="message" />
<button class="send-message" v-on:click="submit">Submit</button>
</div>
</template>
<script>
import $ from 'jquery'
import qs from 'qs'
export default {
data: function () {
return {
message: 'Hello'
}
},
methods: {
submit: function() {
let params = qs.stringify({
'message': this.message
})
$.ajax({
type: 'GET',
url: 'http://127.0.0.1:5000/api' + '?' + params,
success: function(value) {
console.log('success')
console.log(value)
},
error: function(error) {
console.log('error')
console.log(error)
},
})
}
}
}
</script>
<style>
.enter-message {
display: block;
margin: 20px;
padding: 2px;
}
.send-message {
display: block;
margin: 20px;
}
</style>
Command line to run vue serve index.vue
the Quick Start a server ( 127.0.0.1:8080
), powered applications
③ test
Since the difference between the two ports, so there is no doubt that the emergence of cross-domain problems
Below we discuss two common cross-domain solutions to problems, to put the final results
Final Results:
(1) JSONP
In simple terms, JSONP get cross-domain resources by limiting the src attribute <script> tag is not the same origin policy
Specifically, the front end of the function name in the parameter sent a callback function, the back-end return calls this function, and the data on the parameters of this function
Note, JSONP only supports GET method, the front and rear ends of the core code is as follows
Back-end code:
app.get('/api', function(req, res) {
let func = req.query.callback
let data = { 'message': req.query.message }
res.send(func + '(' + JSON.stringify(data) + ')')
})
Front-end code:
methods: {
submit: function() {
let url = 'http://127.0.0.1:5000/api'
let data = { 'message': this.message }
this.jsonp(url, data).then(function(res) {
console.log(res)
})
},
jsonp: function(url /*String*/, data /*Object*/) {
return new Promise(function(resolve, reject) {
window.handleResponse = function(result) {
resolve(result)
}
let script = document.createElement('script')
script.type = 'text/javascript'
script.src = url + '?' + qs.stringify(data) + '&callback=handleResponse'
document.getElementsByTagName('head')[0].appendChild(script)
setTimeout(function() {
document.getElementsByTagName('head')[0].removeChild(script)
}, 1000)
})
}
}
In fact, Node.js and jQuery provides a more convenient way to use JSONP, front and rear ends of the core code is as follows
Back-end code:
app.get('/api', function(req, res) {
res.jsonp({ // 改成 jsonp
'message': req.query.message
})
})
Front-end code:
methods: {
submit: function() {
let params = qs.stringify({
'message': this.message
})
$.ajax({
type: 'GET',
url: 'http://127.0.0.1:5000/api' + '?' + params,
dataType: "jsonp", // 指定 jsonp
success: function(value) {
console.log(value)
},
error: function(error) {
console.log(error)
},
})
}
}
(2) HEARTS
Cross-domain resource sharing (Cross-Origin Resource Sharing, CORS) is defined in the W3C standard
It defines when cross-domain requests resources, how to interact with the server browser, they convey this information via HTTP headers
We only need to modify the HTTP Response returned by the backend to the head, front-end code without modification
Back-end code:
app.get('/api', function(req, res) {
res.header('Access-Control-Allow-Origin', '*') // 加上 HTTP 头部即可
res.json({
'message': req.query.message
})
})
[Read More JavaScript series of articles, look at JavaScript study notes ]