我正在尝试向使用 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/