Error! Get request in Vuejs with axios (401 Unauthorized) - vue.js

when I call the method "getStates" I unfortunately get a 401 (Unauthorized)" . But if call with GET and the same headers in Postman, it works! How i set my GET request headers??
getStates method:
getStates() {
this.axios
.get(
this.baseURL + "states",
{
params: {
id: this.city,
},
headers: {
"Authorization": "Bearer " + this.token
},
})
.then((response) => {
this.states = response.data.data;
console.warn(response.data.data);
})
.catch((err) => {});
this.apiLoaded = true;
}

try this
./App.vue :
<template>
<div id="app">
<button #click="getStatesInfo">Click</button>
<p>{{ states }}</p>
</div>
</template>
<script>
import { getStates } from "./services";
export default {
name: "App",
data() {
return {
states: "",
};
},
methods: {
getStatesInfo() {
getStates()
.then((res) => {
this.states = res;
console.log(res);
})
.catch((error) => {
console.error(error);
});
},
},
};
</script>
./services/index.js :
const baseUrl = "http://localhost:4000/";
const axios = require("axios");
const instance = axios.create({
baseURL: baseUrl,
timeout: 60000,
headers: {
"Authorization": "Bearer " + "your-token",
},
});
export async function getStates() {
const response = await instance.get("/states", {
params: {
id: "param1",
},
});
return response.data;
}

Related

Request failed with status code 401', name: 'AxiosError', code: 'ERR_BAD_REQUEST'

I'm on a page that uses a vue component and one of my patch routes is saying I'm un-authenticated.
<template>
...
<button #click="editPost(attributes.attributes.post_id)"></button>
...
</template>
<script>
export default {
data() {
return {
info: null,
message: null,
postTitle: "",
postContent: ""
}
},
methods: {
editPost(id) { // not working, 401 unauthenticated
console.log('edit post clicked', id);
axios.patch('http://127.0.0.1:8000/api/posts/' + id, {
headers: {
Authorization: 'Bearer 3d58d6cd66e134a59b3a9373a2b4a233e55d00107b9251f654c5c92a2276a1c5'
}
})
.then((response) => {
this.info = response.data;
// this.message = 'Success';
console.log(this.info);
})
.catch((error) => {
console.log(error, error.response.data.message);
this.message = error.response.data.message;
})
},
deletePost(value){
console.log('delete post clicked', value);
}
},
mounted() {
axios.get('http://127.0.0.1:8000/api/posts', { // working as expected, authenticated
headers: {
Authorization: 'Bearer 3d58d6cd66e134a59b3a9373a2b4a233e55d00107b9251f654c5c92a2276a1c5'
}
})
.then((response) => {
this.info = response.data;
this.message = 'Success';
console.log(this.info);
})
.catch((error) => {
console.log(error, error.response.data.message);
this.message = error.response.data.message;
})
}
}
</script>
I dont understand how this can be since I have to authenticate to get the posts on page load and they load fine, with authentication using a Bearer token in header?
Why is the call to axios using a PATCH not working? The PATCH call works in postman fine also.

vue component not displaying computed properties

This is a Vue3 project. When Domains.vue is mounted, getDomains is dispatched to vuex, and the data is properly set as indicated by vue dev tools.
For some reason, the data is not displayed in the template for loop. Perhaps one of you wonderful people can help me figure out why not?
Domains.vue
<template>
<div class="domains">
<h1>This is an domains page</h1>
<ul>
<li v-for="item in domains" :key="item.post_name">
<h3>{{ item.post_title }}</h3>
<p>{{ item.post_excerpt }}</p>
</li>
</ul>
</div>
</template>
<script>
export default {
name: 'Domains',
computed: {
domains() {
return this.$store.state.domains.domains
},
},
mounted() {
this.$store.dispatch('getDomains')
}
}
</script>
vuex store
import { createStore } from 'vuex'
import axios from 'axios'
export default createStore({
state: {
user: {
'id': localStorage.getItem('id'),
'token': localStorage.getItem('token'),
},
domains: {
domains: [],
totalDomains: '',
totalPages: ''
},
},
mutations: {
SET_USER(state, user) {
state.user = user
localStorage.setItem('id', user.id)
localStorage.setItem('token', user.token)
},
DELETE_USER(state) {
state.user = { token: '' }
localStorage.setItem('id', '')
localStorage.setItem('token', '')
},
SET_DOMAINS(state, data, headers) {
state.domains.domains = data
state.domains.totalDomains = headers['X-WP-Total']
state.domains.totalDomains = headers['X-WP-TotalPages']
},
SET_ME(state, data) {
state.user.me = data
},
},
actions: {
login({ commit }, payload) {
return new Promise(async (resolve, reject) => {
try {
const { data } = await axios.post(`http://sslchkr.com/wp-json/jwt-auth/v1/token`, payload)
commit('SET_USER', data)
resolve(data)
} catch(e) {
reject(e)
}
})
},
logout({ commit }) {
commit('DELETE_USER')
},
validate({ state }) {
return new Promise(async (resolve, reject) => {
try {
const { data } = await axios({
url: `http://sslchkr.com/wp-json/jwt-auth/v1/token/validate`,
method: 'post',
headers: {
'Authorization': `Bearer ${state.user.token}`
}
})
//commit('SET_USER', data)
resolve(data)
} catch(e) {
reject(e)
}
})
},
getDomains({ commit, state }) {
return new Promise(async (resolve, reject) => {
try {
const { data, headers } = await axios.get(`http://sslchkr.com/wp-json/sslchkr/v1/author/${state.user.id}/domain`, {
headers: {
Authorization: `Bearer ${state.user.token}`
}
})
commit('SET_DOMAINS', data, headers)
resolve(data)
} catch(e) {
reject(e)
}
})
},
getMe({ commit, state }) {
return new Promise(async (resolve, reject) => {
try {
const { data } = await axios.get(`http://sslchkr.com/wp-json/wp/v2/users/me`, {
headers: {
Authorization: `Bearer ${state.user.token}`
}
})
commit('SET_ME', data)
resolve(data)
} catch(e) {
reject(e)
}
})
},
},
modules: {
}
})
convert this
<li v-for="item in domains" :key="item.post_name">
to
<li v-for="item in domains" :key="item">
and if this doesn't work, add index as key
<li v-for="(item,idx) in domains" :key="idx">
Please disregard this. I jumped the gun and posted the question before I knew what was wrong.

Vue API data is gone on window refresh

When I login I am redirected to secret page which needs JWT authentication. Data is loaded on secret page. And when I refresh the window - data is lost. How can I fix it?
I use eventBus to send a JWT token to sibling template.
Login view method on submit:
submitSignin() {
console.log("submit!");
this.submitted = true;
this.$v.$touch();
if (this.$v.$invalid) {
return; // stop here if form is invalid
}
axios
.post("http://localhost:3000/auth/login", this.authData)
.then((res) => {
this.token = res.data.token;
this.authData.email = "";
this.authData.password = "";
this.$v.$reset();
this.successMsg = "You Sign in Successfully!";
this.$router.push({ path: "/auth/all-users" });
this.$nextTick(() => {
eventBus.$emit("sendtoken", this.token);
});
})
.catch((err) => {
console.log(err.response.data.message);
this.errorMsg = err.response.data.message;
});
},
SecretPage view:
<script>
export default {
name: "SecretPage",
data() {
return {
users: [],
};
},
methods: {
loadUsers() {
let self = this;
eventBus.$on("sendtoken", (token) => {
axios
.get("http://localhost:3000/auth/all-users", {
headers: {
Authorization: `Bearer ${token}`,
},
})
.then((response) => {
console.log(token);
console.log(response.data.users);
self.users = response.data.users;
})
.catch((err) => {
console.log(err);
});
});
},
},
mounted() {
this.loadUsers();
},
};
</script>
loaded users

How to fetch data in Vue 3?

I don't know how to fetch data with Vue 3? I created one action and with this action I am calling endpoint (https://api.openbrewerydb.org/breweries/5494). I didn't get response data.
Endpoint:
import { createStore } from 'vuex'
export default createStore({
state: {
},
mutations: {
},
actions: {
async getData() {
await fetch('https://api.openbrewerydb.org/breweries/5494', {
method: 'get',
headers: { 'Content-type': 'application/json' },
}).then((response) => {
if (!response.ok) {
throw Error(response.statusText);
}
console.log('response: ', response)
}).catch((error) => {
console.log('Looks like there was a problem: \n', error);
});
}
},
modules: {
}
})
Vue component:
<template>
<div #click="loadData">Load Data</div>
</template>
<script>
import { useStore } from 'vuex'
export default {
name: 'HelloWorld',
props: {
msg: String
},
setup () {
const store = useStore()
const loadData = () => {
store.dispatch('getData')
}
return { loadData }
}
}
</script>
As a response I didn't get anything but I should get:
{"id":5494,"name":"MadTree Brewing","brewery_type":"regional","street":"3301 Madison Rd","address_2":null,"address_3":null,"city":"Cincinnati","state":"Ohio","county_province":null,"postal_code":"45209-1132","country":"United States","longitude":"-84.4239715","latitude":"39.1563725","phone":"5138368733","website_url":"http://www.madtreebrewing.com","updated_at":"2018-08-24T15:44:22.281Z","created_at":"2018-07-24T01:34:01.620Z"}
You need to make the data to json
.then(res=>res.json())
this will do the trick for you.
const getData = () => {
fetch('https://api.openbrewerydb.org/breweries/5494', {
headers: { 'Content-type': 'application/json' },
}).then(res=>res.json()).then((response) => {
console.log({ response })
}).catch((error) => {
console.log('Looks like there was a problem: \n', error);
});
}
getData();
If the response fails, it will surely get you to catch.
This answer Should be the accepted answer.
If readers landed here while working through the introductory examples on the Vue.js website, Adarsh's code can be adapted thusly (for Vue.js 3):
<div id="beer">
{{ message }}
</div>
const Breweries = {
data() {
return {
message: ""
}},
mounted() {
fetch('https://api.openbrewerydb.org/breweries/', {
headers: { 'Content-type': 'application/json' },
}).then(res=>res.json()).then((response) => {
this.message = response;
}).catch( (error) => {
this.message = error;
});
}
}
Vue.createApp(Breweries).mount('#beer')
First you must install a package like axios
Then create an object from axios and call the API
import axios from "axios";
export default {
setup() {
function getUsers() {
axios.get("https://jsonplaceholder.typicode.com/users")
.then(function (response) {
// handle success
console.log(response.data);
})
.catch(function (error) {
// handle error
console.log(error);
});
getUsers();
}
return { getUsers };
},
};

TypeError: stripe.redirectToCheckout is not a function in nuxt.js

I am trying to integrate stripe payment gateway. I have a nuxt.js for front-end and adonis.js for backend.
From front-end I am calling an api to backend to create checkoutSession and return the sessionID. I am able to create checkoutSession and return the sessionID and in api response I am calling the
stripe.redirectToCheckout but it is not redirecting rather gives error as stripe.redirectToCheckout is not a function. How can I redirect users to checkout Page?
I have install the stripe-js file also.
import { loadStripe } from '#stripe/stripe-js'
const stripe = loadStripe(process.env.STRIPE_PK)
<button class="btn btn-primary btn-block text-center rounded" #click="checkout()">Buy</button>
import { loadStripe } from '#stripe/stripe-js'
const stripe = loadStripe(process.env.STRIPE_PK)
export default {
methods: {
checkout() {
let params = {
payment_method_types: ['card'],
line_items: [
{
name: 'Buy Now',
images: ['image.jpg'],
amount: 100 + '00',
currency: 'usd',
quantity: 1,
},
],
mode: 'payment',
success_url: `${process.env.URL}/success`,
cancel_url: window.location.href,
}
axios
.post(`${process.env.API_BASE_URL}/stripe/session`, params, {
'Content-type': 'application/json',
Accept: 'application/json',
})
.then((response) => {
this.stripeSession = response.data.data
stripe.redirectToCheckout({sessionId: this.stripeSession})
})
.catch((e) => {
console.log(e)
})
}
},
}
</script>
According to tyhe doc, loadStripe is an async function, try adding await in stripe assignement:
const stripe = await loadStripe(process.env.STRIPE_PK)
Edit:
To get rid of Module parse failed: Cannot use keyword 'await' outside an async function error you just need to add async before your function declaration :
async function myAsyncFunction() {
const test = await myPromise();
}
As I do not have the full definition of your function I cannot show it to you in your code :-(
But a weird solution (mixing 'await' and 'then') would be :
import { loadStripe } from '#stripe/stripe-js';
axios
.post(`${process.env.API_BASE_URL}/stripe/session`, params, {
'Content-type': 'application/json',
Accept: 'application/json',
})
.then(async response => {
this.stripeSession = response.data.data;
const stripe = await loadStripe(process.env.STRIPE_PK);
stripe.redirectToCheckout({ sessionId: this.stripeSession });
})
.catch(e => {
console.log(e);
});
This should work:
import { loadStripe } from '#stripe/stripe-js';
export default {
methods: {
async checkout() {
let params = {
payment_method_types: ['card'],
line_items: [
{
name: 'Buy Now',
images: ['image.jpg'],
amount: 100 + '00',
currency: 'usd',
quantity: 1,
},
],
mode: 'payment',
success_url: `${process.env.URL}/success`,
cancel_url: window.location.href,
};
try {
const { data } = await axios.post(`${process.env.API_BASE_URL}/stripe/session`, params, {
'Content-type': 'application/json',
Accept: 'application/json',
});
this.stripeSession = data.data;
const stripe = await loadStripe(process.env.STRIPE_PK);
stripe.redirectToCheckout({ sessionId: this.stripeSession });
} catch (error) {
console.error(error);
}
},
},
};