【问题标题】:VueJs Axios - Request headersVueJs Axios - 请求标头
【发布时间】:2019-01-04 10:29:49
【问题描述】:

编辑:这可能是 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}");

谢谢。

【问题讨论】:

标签: javascript vue.js axios


【解决方案1】:

Difference between the created and mounted events in Vue.js

阅读答案并尝试使用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)
 }
}

【讨论】:

  • 谢谢,@vladja。我才刚刚开始学习,所以在这里感谢您的回复。我将代码修改为这个 sn-p,然后返回 404:jsfiddle.net/hx74u851/1
【解决方案2】:

你的问题不是标题。您正在正确设置它。它与网址有关。您正在构建您的 URL,如下所示:

url: 'https://demo-api.com/{demoId}?" + $.param(params)',

您的网址字符串错误。它最后有一个额外的报价。这就是您收到 404 错误的原因。这是你需要做的:

url: "https://demo-api.com/{demoId}?" + $.param(params),

另外,如果你使用的是 Vue 而不是 jQuery,那么你不应该使用 $.param 函数。相反,请使用正确的查询字符串模块,如qs。所以你的实际网址应该是:

url: `https://demo-api.com/${demoId}?${qs.stringify(params)}`,

这里我们使用的是 ES2015 字符串插值。

【讨论】:

  • @Thanks,我已更新我的代码以删除它。响应仍返回 404。