Describes cross-origin issues in Vue development mode.
Set Request Header
- Backend settings Request Header
Access-Control-Allow-Credentials: true
AndAccess-Control-Allow-Origin: www.xxx.com
- Frontend post request settings
withCredentials=true
- The request data method code for axios is as follows:
import axios from 'axios'import config from '../config'export default {request (method, uri, data, headerConfig = {withCredentials: true}) {if (!method) { console.error('API function call requires method argument') return}if (!uri) { console.error('API function call requires uri argument') return}let url = config.serverURI + urireturn axios({ method, url, data, ...headerConfig })}}
$. Ajax of jQuery ::
$.ajax({type: "POST",url: "http://www.xxx.com/api.php",dataType: 'json',xhrFields: { withCredentials: true},crossDomain: true}).then((json) => {// balabala...})
Use nodejs as proxy
- The above method requires the backend to work with the header. for front-end beginners like me, all kinds of failures in joint debugging cannot be solved. Therefore, I prefer the following method, in view of the project created using scaffolding vue-cli, the author has provided me with a solution.
- Find config/index. js in the project folder, which contains a row of proxyTable :{}. Here is the interface reserved by the author for us. We will add proxy rules to it.
var path = require('path')module.exports = {build: {env: require('./prod.env'),index: path.resolve(__dirname, '../xxx/index.html'),assetsRoot: path.resolve(__dirname, '../xxx'),assetsSubDirectory: 'static',assetsPublicPath: '/',productionSourceMap: true,productionGzip: false,productionGzipExtensions: ['js', 'css']},dev: {env: require('./dev.env'),port: 8080,assetsSubDirectory: 'static',assetsPublicPath: '/',proxyTable: { '/api': { target: 'http://www.xxx.com/api.php/', changeOrigin: true, pathRewrite: { '^/api': '/' } }},cssSourceMap: false}}
Here, target is the target domain name, And pathRewrite is the conversion rule. When requesting data, you can request the interface address based on the Conversion rule to solve the cross-origin problem! (You can also configure headers and cookis and token)
Jsonp
Jsonp is also a method to solve cross-domain problems, but I have never used it. I checked the information on the Internet. The principle of jsonp is that the introduction of js by script tags is not subject to domain name restrictions, because the script tag is inserted in simulation mode, post requests cannot be used.
The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.