In the beginning of learning Vue, today encountered a cross-domain problem that let my brain pain, but in my own writing, Baidu out of several methods, have tried, not what too big help. So I want to borrow the nuggets to record this mistake, I hope the next time when the problem can be quickly solved, I also hope to be able to give the same as me, in this kind of problem, bring help. Although most of the people who publish work in the Nuggets are great, this is my first article on the Nuggets, so please don’t spray if you don’t like it, thanks!
The following is the browser error message:
The error message is: The security policy of the browser is blocked by the CORS policy, that is, the same origin policy.
The same origin policy provides the following requirements: 1. Protocol name, 2. Domain name/IP address, and 3. If one of them is different, the same origin policy is violated and cross-domains are generated. Only if all of them are the same, the same origin policy is met. Hey hey, sorry, and the title is a little far away, so let’s continue to return to the topic.
Here’s what happened to me: I used a Baidu search interface, used watch to monitor, and then got its data.
Here’s the code I wrote:
// I'm using an online lead-in
<script src="https://cdn.bootcss.com/vue/2.6.11/vue.js"></script>
<script src="https://cdn.bootcdn.net/ajax/libs/axios/0.21.0/axios.js"></script>
/ / HTML code
<div id="app">
<input type="text" v-model="inputValue" />
<input type="button" name="" value="Google it." />
</div>
/ / network interface (baidu search) : https://www.baidu.com/sugrec?prod=pc&wd=1
/ / the vue code
const vm = new Vue({
el: '#app'.data() {
return {
inputValue: ' '}; },/ / monitor
watch: {
inputValue() {
axios({
method: 'GET'.url: `https://www.baidu.com/sugrec`.params: {
prod: 'pc'.wd: this.inputValue,
},
})
.then((response) = > {
console.log('Request successful :', response);
})
.catch((err) = > {
console.log('Request failed :', err); }); ,}}});Copy the code
The code looks fine, but the cross-domain problem in Figure 1 still occurs.
Solution 1:(Browser side debugging scheme)
2. Right-click to create a new browser shortcut. 3. Go to desktop shortcut → Right click → Properties → Shortcut TAB → Target and append the following parameters
–user-data-dir=”c:\ChromeDebug” –test-type –disable-web-security
Confirm save. Click the shortcut to open the browser, enter the original link address in the address bar, and press Enter
How to enable Ajax cross-domain access debugging in Chrome? Click to view
Solution 2:(JSONP solution)
// JSONP private programme:
// Take advantage of the fact that script tags do not have cross-domain restrictions, instead of sending requests with AJAX
// Good compatibility
// Disadvantages: only support GET requests (because script can only send GET requests)
// CDN introduces jquery code
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.js"></script>
/ / monitor
watch: {
inputValue() {
$.ajax({
// url:'https://www.baidu.com/sugrec?prod=pc&wd='+this.inputValue,
type: 'GET'.url: `https://www.baidu.com/sugrec`.dataType: 'jsonp'.// Process the jSONp request, specifying the type of data to be returned by the server
data: {
prod: 'pc'.// Data carries the requested parameters
wd: this.inputValue,
},
success(res) {
console.log('Request successful', res);
},
error(err) {
console.log('Request failed', err); }}); }},Copy the code
Solution 3:(Vue scaffold 3 uses proxy solution)
// code inside app.vue
<template>
<div>
<input type="text" v-model="inputValue" />
<input type="button" name="" value="Google it." />
</div>
</template>
<script>
/ / network interface (baidu search) : https://www.baidu.com/sugrec?prod=pc&wd=1
import axios from "axios"; / / introduce axios
export default {
name: "App".data() {
return {
inputValue: ""}; },watch: {
inputValue() {
axios({
method: "GET".url: "apis/sugrec? prod=pc&wd=" + this.inputValue,// Use the proxy apis
})
.then((response) = > {
console.log("Request successful", response);
})
.catch((err) = > {
console.log("Request failed", err); }); ,}}};</script>
<style scoped>
</style>
Copy the code
Vue.config.js:
module.exports = {
devServer: {
host: 'localhost'.// Local domain name/IP address
port: '8080'./ / the port number
proxy: { // Configure cross-domain
'/apis': {
target: 'https://www.baidu.com/'.// The address for the proxy
secure: false.// If the interface is not HTTPS, do not set this parameter
changeOrigin: true.// Allow cross-domain
pathRewrite: {
'^/apis': ' '.// The path is rewritten to change the prefix /apis to "/", which can also be interpreted as "/apis" instead of the address in target
/ / if itself has "/ API interface address this common prefix, that is to say, https://www.exaple.com/api, you can delete pathRewrite, if not add},},},},},};Copy the code
Thank you for your tips. In addition to the above browser and JSONP solutions, there are also cORS official solutions recommended by everyone in the comment area, proxy server proxy solutions…