我正在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相关问答推荐

为什么我的数组在 onBeforeMount 函数中不为空,但在 onMounted 函数中为空

我如何使用vuejs访问彼此嵌套的json对象

使用 cypress 进行 e2e 测试的 vuejs 期间出现 Webpack 错误

vue 计算的 ant watch 不会在嵌套属性更改时触发

如何在 vue 路由中导航到 Bootstrap-vue 选项卡中的特定选项卡?

无需直接 DOM 操作即可绘制d3-axis

aspnet core如何在deploy上构建webpack

如何渲染数组以 Select 选项 vue.js

VueJS:向左,元素的顶部位置?

为什么 Vue 路由/Webpack 开发服务器现在在页面刷新时显示无法获取/路径?

如何获取 Vue 路由历史记录?

使用 Vue.js (cdn) 在特定元素上切换显示/隐藏

POST 文件连同表单数据 Vue + axios

VS代码中的红点是什么意思

将 SignalR 与 Vue.js 和 Vuex 集成

在 vue.js 组件中react this.props.children

laravel vuejs/axios put request Formdata 为空

如何从浏览器的源中删除 webpack://

Apollo 客户端在向服务器发送Mutations 时返回400(错误请求)错误

vue-cli@3 没有可用于依赖类型的模块工厂:CssDependency