Vue cross-domain solution

一个新手
Release: 2017-10-16 10:43:56
Original
2231 people have browsed it

In the vue project, when the front-end and back-end perform data requests or submissions, if the back-end does not set cross-domain settings, the front-end will report "No 'Access-Control-Allow-Origin' header is present on the" when debugging the code locally. requested resource." This cross-domain error.

If you want to debug normally locally, there are three solutions:

1. Change the header in the background


header('Access-Control-Allow-Origin:*');//允许所有来源访问 header('Access-Control-Allow-Method:POST,GET');//允许访问的方式   
Copy after login

This way you can request data across domains.

2. Use jsonp provided by JQuery (Note: jquery is introduced in vue and Baidu is used by Baidu)


##

methods: { getData () { var self = this $.ajax({ url: 'http://f.apiplus.cn/bj11x5.json', type: 'GET', dataType: 'JSONP', success: function (res) { self.data = res.data.slice(0, 3) self.opencode = res.data[0].opencode.split(',') } }) } }
Copy after login

This method can also solve cross-domain problems question.

3. Use http-proxy-middleware proxy solution (the project is built using vue-cli scaffolding)

For example, the requested url: "http://f.apiplus.cn/bj11x5.json "

1. Open config/index.js and add the following code in proxyTable:


proxyTable: { '/api': { //使用"/api"来代替"http://f.apiplus.c" target: 'http://f.apiplus.cn', //源地址 changeOrigin: true, //改变源 pathRewrite: { '^/api': 'http://f.apiplus.cn' //路径重写 } } }
Copy after login

2. Use it directly when requesting data using axios" /api”:


getData () { axios.get('/api/bj11x5.json', function (res) { console.log(res) })
Copy after login

Use this method to solve cross-domain problems. If you still use this method when packaging and deploying, problems will arise. The solution is as follows:


let serverUrl = '/api/' //本地调试时 // let serverUrl = 'http://f.apiplus.cn/' //打包部署上线时 export default { dataUrl: serverUrl + 'bj11x5.json' }
Copy after login
Define a serverUrl to replace our "/api" during debugging. When packaging, you only need to replace "http://www.xxx. com" to replace this "/api".

The above is the detailed content of Vue cross-domain solution. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
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
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!