编辑:这可能是CORS的问题,我在本地主机上.
在Javascript中,我可以设置请求头,获取并返回如下响应:
$(function() {
var params = {
// Request parameters
};
$.ajax({
url: "https://demo-api.com/",
beforeSend: function(xhrObj){
// Request headers
xhrObj.setRequestHeader("Ocp-Apim-Subscription-Key","{API KEY}");
},
type: "GET",
// Request body
data: "{body}",
})
.done(function(data) {
alert("success");
})
.fail(function() {
alert("error");
});
});问题:
我想学习VueJs,并希望用VueJs + Axios来复制它,但是对于如何像上面的JS一样设置请求头,我感到很困惑。
这里是我失败的尝试:
new Vue({
el: '#app',
data () {
return {
info: null,
loading: true,
errored: false,
response: false
}
},
mounted () {
axios({
method: 'get',
url: 'https://demo-api.com/',
headers: {
'Ocp-Apim-Subscription-Key': 'API KEY',
}
})
.then(response => {
console.log(response)
this.response = true
})
.catch(error => {
console.log(error)
this.errored = true
})
.finally(() => this.loading = false)
}
})如何像在上面的JS中那样,具体地设置请求头。我想学习如何在Vue/Axios中实现以下内容。
xhrObj.setRequestHeader("Ocp-Apim-Subscription-Key","{API KEY}");谢谢。
发布于 2018-07-27 10:21:39
阅读答案,尝试使用created()生命周期挂钩而不是mounted()
此外,您可以使用此头创建axios的单独实例,然后在您的代码中使用它:
axios-demo-api.js
import axios from 'axios'
const instance = axios.create({
baseURL: 'https://demo-api.com',
headers: {'Ocp-Apim-Subscription-Key': 'API KEY'} //don't forget to change API key to your exact key
})
export default instance用法:
import axiosInstance from 'axios-demo-api';
export default {
created() {
axiosInstance.get('/{demoId}?' + $.param(params))
.then(response => {
console.log(response)
this.response = true
})
.catch(error => {
console.log(error)
this.errored = true
})
.finally(() => this.loading = false)
}
}发布于 2018-07-27 10:27:51
你的问题不在于标题。你正在正确地设置它。这与URL有关。您正在像这样构造您的URL:
url: 'https://demo-api.com/{demoId}?" + $.param(params)',您的URL字符串是错误的。它有一个额外的报价在结尾。这就是你有404错误的原因。这就是你需要做的:
url: "https://demo-api.com/{demoId}?" + $.param(params),另外,如果您使用的是Vue而不是jQuery,那么就不应该使用$.param函数。相反,使用适当的查询字符串模块(如qs )。所以您的实际URL应该是:
url: `https://demo-api.com/${demoId}?${qs.stringify(params)}`,这里我们使用ES2015字符串插值。
https://stackoverflow.com/questions/51555565
复制相似问题