由于图灵机器人的访问接口更改了,发现以前的资料都不适用于跨域访问接口,于是我学习了如何通过配置本地代理服务器,又结合当前的接口格式进行了修改,最后成功访问了图灵机器人V2接口。
先附上代码
APP.vue中的生命周期钩子函数created()
created(){
//当这个请求成功返回响应时,.then() 方法中的回调函数将会被执行。
//res 是表示 HTTP POST 请求成功返回的响应对象。
axios.post('/api',{
"reqType":0,
"perception": {
"inputText": {
"text": "这小机器人"
},
"selfInfo": {
"location": {
"city": "广州"
}
}
},
"userInfo": {
"apiKey": "(换成自己的apiKey)",
"userId": "(换成自己的userId)"
}
}).then(res=>{
let text= res.data.results[0].values.text;
console.log(text)
}
)
}
创建vue.config.js文件
const { defineConfig } = require('@vue/cli-service')
module.exports = defineConfig({
transpileDependencies: true,
devServer:{
proxy:{
//这个/api表示本地服务器会拦截本地发送的以api为开头的请求
'/api':{
target:'http://openapi.turingapi.com/',
changeOrigin: true,
pathRewrite: {'^/api': '/openapi/api/v2'}
}
}
}
})
运行指令 npm run serve
机器人回复结果在results参数中
附上图
这个代码的工作原理如下,假设本地运行的地址是localhost:8080,通过axios发送一个post请求到接口‘/api’,那这个请求的全部内容是localhost:8080/api,这个请求会被本地的代理服务器给拦截,原因是代理服务器会拦截以/api开头的所有请求,再代为发送到我们target中设置的域名,再通过重写pathRewrite,将这个请求中的"/api"全部都改成'/openapi/api/v2',将域名和接口都修改后,我们可以看到,请求最终是发送到http://openapi.turingapi.com/openapi/api/v2,这个图灵机器人的v2接口了。