[英]VueJs Axios - Request headers
編輯:這可能是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}");
謝謝。
閱讀答案並嘗試使用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)
}
}
您的問題不是標題。 您正在正確設置。 它與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: `https://demo-api.com/${demoId}?${qs.stringify(params)}`,
在這里,我們使用ES2015字符串插值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.