1.请求第三方接口,vue2 在 vue.config.js
下配置跨域代理
module.exports = {
publicPath: process.env.NODE_ENV=='development'?'/':'./',
lintOnSave: false,
devServer: {
// publicPath: '',
publicPath: process.env.NODE_ENV=='development'?'/':'./',
disableHostCheck: process.env.NODE_ENV === "development",
// host: '127.0.0.1',
port: 8089,
proxy: {
// 设置代理
// proxy all requests starting with /api to jsonplaceholder
'/dhl': {
target: 'https://xxxxx.com', // 真实请求的目标地址
ws: true, // 是否启用websockets
changeOrigin: true,
pathRewrite: { '^/dhl': '' }
}
}
}
}
2.使用base64
安装依赖
npm install --save js-base64
main.js引入(或者在使用的界面引入)
import {Base64} from 'js-base64'
Vue.prototype.$Base64 = Base64;
页面使用
let encPass=this.$Base64.encode(password);//加密
let decPass=this.$Base64.decode(encPass);//解密
3.请求接口
let data = {
productCode: "D",
localProductCode: "D",
};
// "Basic Auth"
const tok = "用户名:密码";
const hash = Base64.encode(tok);
const Basic = "Basic " + hash;
console.log({ Basic });
axios.defaults.baseURL = "/dhl"; // 设置请求URL
axios({
url: "/XXXXX", //接口
method: "post",
data: data,
auth: { //主要不要漏掉,不加auth它返回一个401错误
username: "XXXXX",
password: "XXXXX",
},
headers: {
Authorization: Basic,
"Shipping-System-Platform-Version": "1.0",
"Message-Reference": "d0e7832e-5c98-11ea-bc55-0242ac18",
"Message-Reference-Date": "Thur, 10 Feb 2023 09:39:00 GMT+08:00",
"Shipping-System-Platform-Name": "MyDHL API Test",
},
}).then((res) => {
console.log(res);
});
网友评论