設(shè)置請(qǐng)求頭部
Access-Control-Allow-Credentials: true和Access-Control-Allow-Origin: www.xxx.com 前端post請(qǐng)求設(shè)置withCredentials=true 這里用了axios的請(qǐng)求數(shù)據(jù)方法代碼如下: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 })}}jQuery的$.ajax::
$.ajax({type: "POST",url: "http://www.xxx.com/api.php",dataType: 'json',xhrFields: { withCredentials: true},crossDomain: true}).then((json) => {// balabala...})使用nodejs做代理
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}}這里target為目標(biāo)域名,pathRewrite為轉(zhuǎn)換規(guī)則,請(qǐng)求數(shù)據(jù)時(shí)將接口地址 根據(jù)轉(zhuǎn)換規(guī)則請(qǐng)求就可以解決跨域啦!(這里也可以配置headers,設(shè)置cookis,token等)
jsonp
jsonp也是一種解決跨域的方法,不過我從來沒有用過,在網(wǎng)上查了下資料,jsonp的原理是script標(biāo)簽引入js是不受域名限制的, 由于是模擬插入script標(biāo)簽, 所以不可以用post請(qǐng)求。
以上就是本文的全部內(nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持錯(cuò)新站長站。
新聞熱點(diǎn)
疑難解答
圖片精選