我正在try 向使用标头的后端发送请求,请问如何添加标头

这是我的脚本标签

<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);
      }
    }
  }
 }

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

推荐答案

您的代码有一些问题.例如,您没有将标题定义为变量,也没有将其添加到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正常工作,需要在axios调用之前添加await.

希望这有帮助.

Vue.js相关问答推荐

Nuxt3 / Vue3 - 当属性更改时如何动态更改渲染组件?

如何向 添加方法和 v-model?

在 v-for 中定义变量有什么问题吗?

如何 for each 动态创建的按钮/文本字段设置唯一变量?

在 Vuex Store 模块中使用 Vue.js 插件

在 vuejs 中显示两个组件,但只显示一个,为什么?

如何使用带有自定义标签和类的`transition-group`

带有 vue.js 的 img 网址

在 Vuejs 中Watch观察 window.scrollY 的变化

如何在不实例化根实例的情况下使用 vue 组件?

单击链接会更改 url,但不会更改页面上的内容/数据

如何将 mapActions 与 vue + Typescript 类组件一起使用?

Vuetify 输入自动完成错误

Javascript/vue.js 接收json

VueJS 通过渲染传递数据

Nuxt 应用程序在刷新动态路由时返回 404(Tomcat 服务器)

如何异步验证 Vuetify 文本字段?

用于本地编辑的 Vuex 克隆对象

如何设置 :id 前缀字符串?

Vue 3 – 渲染无法动画的非元素根 node