vue.js - 如何使用 async/await 在 vue js 中添加 header

标签 vue.js vuejs2

我正在尝试向使用 header 的后端发送请求,请问如何添加 header

这是我的脚本标签

<script>
import axios from "axios";
export default {
  data: () => ({
    fullName: "",
    streetAddress1: ""
  }),
  created() {
    //user is not authorized
    if (localStorage.getItem("token") === null) {
      this.$router.push("/login");
    }
  },
 
  methods: {
    
    async onAddAddress() {
       const token = localStorage.getItem("token");
          headers: {
          "Content-Type": "application/json",
          Authorization: "Bearer" + token,
          "x-access-token": token
        }
      try {
        let data = {
          fullName: this.fullName,
          streetAddress: this.streetAddress1
        };
   const response = axios
          .post("http://localhost:5000/api/addresses", data)
          .then(res => {
            
            console.log(res);
            
          });

        console.log(response);
      } catch (error) {
        console.error("error >>", error);
      }
    }
  }
 }

这段代码给了我一个错误,请问我该怎么做

最佳答案

您的代码存在一些问题。例如,您没有将 headers 定义为变量,也没有将其添加到 axios request as a third argument 中。 。我认为你需要这样的东西:

 async onAddAddress() {
    
     const token = localStorage.getItem("token");

     /// define headers variable
     const headers = { 
         "Content-Type": "application/json",
         Authorization: "Bearer" + token,
         "x-access-token": token
     };

     let data = {
        fullName: this.fullName,
        streetAddress: this.streetAddress1
     };
     
     try {
        /// config as the third argument.
        conts result = await axios.post("http://localhost:5000/api/addresses", data, { headers });
     
        console.log(result);
     }
     catch (error) {
        console.error("error >>", error)      
     }

 }

要使 async/await 正常工作,您需要添加 await在 axios 调用前面。

希望这有帮助。

关于vue.js - 如何使用 async/await 在 vue js 中添加 header ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73005164/

相关文章:

vue.js - 如何在 Vue 3 中使用 SSR

javascript - 使用 Express 下载图像并使用 AJAX 在 Vue 中显示

javascript - 时间序列流,删除 x 轴上的上午/下午和 24 小时格式

javascript - Vue.js 2 和 Axios 范围问题

javascript - vue.js - 如何监视嵌套对象的属性并获取索引?

python - Django admin 中的多张图片上传

javascript - vue-datepicker 禁用 before 和 from

javascript - 数组更改时 VueJS dom 不刷新

javascript - 使用 vue init 创建的应用程序抛出错误

vue.js - Vuejs : how to mix static and dynamic content in template?