【webpack】解決axios跨域

1、通過NPM安裝http-proxy-middleware模塊:

npm install --save-dev http-proxy-middleware

2、webpack配置http-proxy-middleware模塊:
// webpack.config.js
//...
const proxy = require('http-proxy-middleware');

const config = {
  devServer:{
        host: '本地IP',
        port: 8080,  //啟動該項目的端口號
        proxy:{
            '/api':{
                target: '訪問后端IP:端口號',
                changeOrigin: true,
                pathRewrite: {
                    '^/api': '/'
                }
            }
        }
    },
  entry: {
        main: './main'
  },
  //...
};

module.exports = config;
3、axios配置:

axios是基于Promise的HTTP庫,同時支持前端和Node.js。
a)首先用NPM安裝axios:
npm install axios --save
b)在項目根目錄下創(chuàng)建libs文件夾,并在libs下新建util.js文件,項目中使用的工具函數(shù)可以在這里封裝。例如axios的封裝:

// axios.js
import axios from 'axios';

// 基本配置
const Util = {
    imgPath: '',
    apiPath: '/api'
};

// Ajax通用配置
Util.ajax = axios.create({
    baseURL: Util.apiPath
});

// 添加響應(yīng)攔截器
Util.ajax.interceptors.response.use(res => {
    return res.data;
});

export default Util;
4、調(diào)用axios請求API:
//導(dǎo)入util.js文件
import $ from './../libs/util.js';
//GET請求:
$.ajax({
        url: url,  //url為請求的接口
        method: 'GET',
        params: params  //接口連接帶的參數(shù),沒有可以為null
    }).then(res => {
        console.log(res)
    }).catch(err => {
        console.log(err)
    });

//POST請求:
$.ajax({
        url: url,  //url為請求的接口
        method: 'POST',
        data: data  //post請求所需的數(shù)據(jù)
    }).then(res => {
        console.log(res)
    }).catch(err => {
        console.log(err)
    });
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容