如何使用vue实现跨域访问第三方http请求
作者:慧香一格
这篇文章主要介绍了如何使用vue实现跨域访问第三方http请求,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考下吧
1、需要配置vue的拦截器vue.config,js
代码如下:
const path = require('path')
const url = 'http://127.0.0.1:19043/'
module.exports = {
dev: {
// Paths
assetsSubDirectory: 'static',
assetsPublicPath: '/',
proxyTable: {
'/aa/bb': { // 前端 包含/aa/bb 的请求就被拦截
target: url, // 拦截后的目标url
changeOrigin: true, // 是否跨域 当前设为跨域
// secure: true,
pathRewrite: {
'^/aa/bb': '' // 会对匹配到的请求做重写,
}
}
}
},2、引用 axios
npm install axios
import axios from 'axios';
// 创建axios实例
const instance = axios.create({
baseURL: 'http://127.0.0.1:19043/aa/bb', // 目标服务器的URL
timeout: 1000, // 请求超时时间
headers: {
'Content-Type': 'application/json',
'Custom-Header': 'your-custom-value' // 你想设置的header
}
});
// 发送请求
instance.get('/someEndpoint')
.then(response => {
// 处理响应
console.log(response.data);
})
.catch(error => {
// 处理错误
console.error(error);
});
————————————————
版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
原文链接:https://blog.csdn.net/xiaozukun/article/details/1366012423、被请求端需要设置允许跨域
Access-Control-Allow-Origin:*
Access-Control-Allow-Methods:"POST, GET, OPTIONS, DELETE"
Access-Control-Request-Headers: “自己定义的hear,多个时用逗号隔开”
到此这篇关于使用vue 实现跨域访问第三方http请求的文章就介绍到这了,更多相关vue跨域访问内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
