Javascript 使用Axios请求HTTP登录Vue
我是Vue的新手,我正在尝试向我的后端发出HTTP请求 当我在浏览器中检查时,我从/login获得访问令牌,但在api/users中我得到“令牌无效”。如何获取api/用户数据Javascript 使用Axios请求HTTP登录Vue,javascript,vue.js,http,axios,Javascript,Vue.js,Http,Axios,我是Vue的新手,我正在尝试向我的后端发出HTTP请求 当我在浏览器中检查时,我从/login获得访问令牌,但在api/users中我得到“令牌无效”。如何获取api/用户数据 import axios from "axios"; export default { name: "login", async created() { const response = await axios.get("api/users",
import axios from "axios";
export default {
name: "login",
async created() {
const response = await axios.get("api/users", {
headers: {
Authorization: "Bearer " + localStorage.getItem("token")
}
});
console.log(response);
},
data() {
return {
showError: false,
email: "",
password: "",
};
},
methods: {
async EnvioLogin() {
try {
const response = await axios.post("api/auth/login", {
email: this.email,
password: this.password,
});
localStorage.setItem("token", response.data.token);
const status = JSON.parse(response.status);
if (status == "200") {
console.log(response);
this.$router.push("intermediorotas");
}
} catch (error) {
this.showError = true;
setTimeout(() => {
this.showError = false;
}, 3000);
}
},
},
您可以创建一个服务来调用后端,我想问题在于urlhttp://localhots:3000/api,你错过了这部分http://localhots:3000
import axios from 'axios'
const client = axios.create({
baseURL: 'http://localhots:3000/api',
headers: {
'Content-Type': 'application/json',
},
})
export default client
然后导入服务
import myService from './myService'
await myService.get(`/auth/login`, {})
您可以创建一个服务来调用后端,我想问题在于urlhttp://localhots:3000/api,你错过了这部分http://localhots:3000
import axios from 'axios'
const client = axios.create({
baseURL: 'http://localhots:3000/api',
headers: {
'Content-Type': 'application/json',
},
})
export default client
然后导入服务
import myService from './myService'
await myService.get(`/auth/login`, {})
created
hook在envirologin
之前运行。。。所以,当然令牌还没有设置好。。。还有。。。什么是const status=JSON.parse(response.status)代码>正在做<代码>已创建
钩子在envirologin
之前运行。。。所以,当然令牌还没有设置好。。。还有。。。什么是const status=JSON.parse(response.status)代码>正在做!!!我在axios.js中使用:从“axios”导入axios-axios.defaults.baseURL=''@Guilherme则不使用baseURL:“”;我在axios.js中使用:从“axios”导入axios-axios.defaults.baseURL=''@Guilherme则不使用baseURL:“”;