目前解決跨域主要的方案有:
jsonp(淘汰)
cors
http proxy
此處介紹的使用devServer解決跨域,其實原理就是http proxy
將所有ajax請求發送給devServer服務器,再由devServer服務器做一次轉發,發送給數據接口服務器
由於ajax請求是發送給devServer服務器的,所以不存在跨域,而devServer由於是用node平台發送的http請求,自然也不涉及到跨域問題,可以完美解決!
服務器代碼(返回一段字符串即可):
const express = require('express') const app = express() // const cors = require('cors') // app.use(cors()) app.get('/api/getUserInfo', (req, res) => { res.send({ name: '黑馬兒', age: 13 }) }); app.listen(9999, () => { console.log('http://localhost:9999!'); });
前端需要配置devServer的proxy功能,在webpack.dev.js中進行配置:
devServer: { open: true, hot: true, compress: true, port: 3000, // contentBase: './src' proxy: { '/api': 'http://localhost:9999' } },
意為前端請求/api的url時,webpack-dev-server會將請求轉發給http://localhost:9999/api處,此時如果請求地址為http://localhost:9999/api/getUserInfo,只需要直接寫/api/getUserInfo即可,代碼如下:
axios.get('/api/getUserInfo').then(result => console.log(result))