Ok, so i have the following method. Basically I am calling an API backend, posting username and password, and if those pass, in the response, the server sends me a 200 status. What I want to do, is in the response, after I get the status, run an if/else, so if the status is 200, redirect, else display an error message. every time i try to use 'this.$router.push('/any route here')',
I get an error: 'homepage.vue?3ec6:72 Uncaught (in promise) TypeError: Cannot read property '$router' of undefined'.
But if i use the same route at the top of the method, outside the axios call, it works fine.
So what am i missing here?
hero_login: function(event){
event.preventDefault();
axios.post('API call here',
{
service:'client',
user: this.user_email,
password: this.user_password,
json:true
})
.then(function(response){
const status =
JSON.parse(response.data.response.status);
console.log(status);
})
}
You have to define this outside axios methods because this inside axios refers to the axios object, not the vue component:
hero_login: function(event) {
let self = this;
event.preventDefault();
axios.post('API call here',
{
service:'client',
user: this.user_email,
password: this.user_password,
json:true
})
.then(function(response){
const status =
JSON.parse(response.data.response.status);
//redirect logic
if (status == '200') {
self.$router.push('/any route here');
}
})
}
}
Use route name
this.$router.push({name: 'home'});
this.$router.replace({name: 'home'});
Use route URL
this.$router.push('/home');
this.$router.replace('/home');
Such as Vue Router Documentation
please use this.$router.push('/home')
You can use easily redirect it by using,
.then(data => {
'this.$router.replace({ name: "home" });
});
OR,
.then(data => {
'this.$router.push({ name: "home" });
});
Related
i'm trying to store token in my local storage but google chrome doesn't store the token even after getting a successful response from my backend
this is my template
<br>EMAIL:
<input type="text" v-model="email">
<br>PASSWORD:
<input type="password" v-model="password">
<br>
<button #click="submit">signup</button>
this is my script tag, if there's token is should go to the "/" but it keeps redirecting me back to login
<script>
import axios from "axios";
export default {
data: () => ({
email: "",
password: ""
}),
methods: {
async submit() {
return axios({
method: "post",
data: {
email: this.email,
password: this.password
},
url: "http://localhost:5000/api/auth/login",
headers: {
"Content-Type": "application/json"
}
})
.then(res => {
console.log(res);
this.$router.push({ path: "/" });
})
.catch(error => {
const message = error.response.data.message;
});
},
clear() {
this.$refs.form.reset();
}
}
};
</script>
this is the response i get in my console
{
"success": true,
"token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJyZXNldExpbmsiOiJleUpoYkdjaU9pSklVekkxTmlJc0luUjVjQ0k2SWtwWFZDSjkuZXlKZmFXUWlPaUkyTWpJNFlqWXhaakpoWTJJM1lqaGtabVF3WlRKaU5qY2lMQ0pwWVhRaU9qRTJOVGs1T1RVNU56WXNJbVY0Y0NJNk1UWTFPVGs1TmpnM05uMC5DakRLOURoR3FqbTJqLVdNd3dhdUxxdGY2MmV4NVd3VnZtVnEyWlpJNGxzIiwiX2lkIjoiNjIyOGI2MWYyYWNiN2I4ZGZkMGUyYjY3IiwibmFtZSI6InRvYmkiLCJlbWFpbCI6InRvbHVhcmVqaWJhZGV5QGdtYWlsLmNvbSIsInBhc3N3b3JkIjoiJDJhJDEwJDZWbzVYajBJc1JOWG5tbldvb1JMak9qa3AwVnJWQ1QwNnBzcVpBcDZ6RW9HMld1MzUxbm1pIiwiX192IjowLCJpYXQiOjE2NjAwMjcxOTAsImV4cCI6MTY2MDYzMTk5MH0.KaSGPy3arsd5N5Ef-yDgUWV2zpYzuZ16YT1Hqe19eec"
}
even with the token i get if i check my application tab in my dev tools i dont see any token, which means i can't access any of my route please how can i go about this, tried downgrading chrome but still same problem
you are not storing the token in the browser that's why.... in your .then function add
localStorage.setItem("token", response.data.token);
If you want store token to local storage
....
.then(res => {
console.log(res);
localStorage.setItem('token', res.token) // you need add this line
this.$router.push({ path: "/" });
...
there is nothing in your code that would suggest that the token is actually saved anywhere. you're just logging out the response data.
localStorage.setItem('token', res.token)
and when you wish to use that token
let token = localStorage.getItem('token')
Firstly, in the code you've provided you aren't setting any values into the Local Storage as you've claimed.
To set your token into Local Storage, use this in then then() block:
localStorage.setItem('token', res.token);
Secondly, you haven't added any conditionals to check if a token exists and to redirect to a page based on it, as you've claimed.
Depending on your need, add an if condition and check if the token exists in the Local Storage (and maybe if its valid too), and then specify the redirection.
if (localStorage.getItem('token') && isTokenValid()) {
this.$router.push({ path: "/" });
} else {
this.$router.push({ path: "/login" });
}
res.cookie("jwtoken", token, {
expires: new Date(Date.now() + 25892000000),
httpOnly: true,
});
use this code to store token after generating token in login backend part
I got a serverless Netlify function like this:
exports.handler = async function(event, context) {
return {
statusCode: 200,
body: JSON.stringify({message: "Hello World"})
};
}
When called by this url <site-name>/.netlify/functions/helloworld
I do get the message {"message":"Hello World"}
I also got a pages/api/mailingList.js Nextjs API endpoint:
const axios = require('axios');
export default async function handler(req, res) {
//console.log(req.query.mail);
if (req.method === "PUT") {
axios
.put(
"https://api.sendgrid.com/v3/marketing/contacts",
{
contacts: [{ email: `${req.query.mail}` }],
list_ids: [process.env.SENDGRID_MAILING_LIST_ID],
},
{
headers: {
"content-type": "application/json",
Authorization: `Bearer ${process.env.SENDGRID_API_KEY}`,
},
}
)
.then((result) => {
res.status(200).send({
message:
"Your email has been successfully added to the mailing list. Welcome 👋",
});
})
.catch((err) => {
res.status(500).send({
message:
"Oups, there was a problem with your subscription, please try again or contact us",
});
console.error(err);
});
}
}
This mailing list API endpoint, do work when using curl from the terminal with PUT as the method:
curl -X PUT -d mail=helloworld#gmail.com https://netlify.app/api/mailingList
The API endpoint also work from the URL (/api/mailingList?mail=helloworld#gmail.com) when removing the if (req.method === "PUT") { part from the mailingList.js
However, I am NOT able to get the API endpoint to be called from within the Netlify function.
(Preferably the mailingList API should be possible to call multiple times with different mailing list IDs from the Netlify function helloworld.js based on different logic /api/mailingList?mail=helloworld#gmail.com&listid=xxx)
To get the API endpoint to be called at all, from the function, I have tried adding a axios call from the helloworld.js to mailingList.js like this
const axios = require('axios');
exports.handler = async function(event, context) {
const mail = "helloworld#gmail.com";
// add to mailinglist
axios
.put("/api/mailingList?mail="+mail)
.then((result) => {
if (result.status === 200) {
toast.success(result.data.message);
}
})
.catch((err) => {
console.log(err);
});
}
This result in the following error from the browser: error decoding lambda response: invalid status code returned from lambda: 0
(I do not get any error msg from the Netlify log, either helloworld.js or mailingList.js)
Clearly, there is something wrong with how I call the mailigList.js from helloworld.js. Would greatly appreciate if some one could give me some advice and show me what I am doing wrong.
How can I call the API endpoint (mailigList.js) from within the Netlify function helloworld.js? (Preferably multiple times with different mailing list IDs: /api/mailingList?mail=helloworld#gmail.com&listid=xxx)
Found the solution in this article: https://travishorn.com/netlify-lambda-functions-from-scratch-1186f61c659e
const axios = require('axios');
const mail = "helloworld#gmail.com";
exports.handler = (event, context, callback) => {
axios.put("https://<domain>.netlify.app/api/mailingList?mail="+mail)
.then((res) => {
callback(null, {
statusCode: 200,
body: res.data.title,
});
})
.catch((err) => {
callback(err);
});
};
I want to navigate manually to home page after login in callback.
methods: {
async userLogin() {
var session_url = "/api/v1/authenticate";
axios
.post(session_url, this.login, {})
.then(function (response) {
console.log("Authenticated", response.data.access_token);
window.localStorage.setItem("token", response.data.access_token);
// Manually trigger route here.
})
.catch(function (error) {
console.log("Error on Authentication", error);
});
},
},
To manually trigger route, you can use below code, where / is home route.
Note: No need to import anything as $router is globally available.
this.$router.push("/" )
I have a simple like this in one of my component:
componentDidMount() {
axios
.get(
API_URL +
"oauth2/authorize?client_id=" +
API_CLIENT_ID +
"&response_type=token"
)
.then(function (response) {
console.log(response);
})
.catch(function (error) {
// handle error
console.log(error);
})
.then(function () {
// always executed
});
}
however, i would like to parse the callback url which is from imgur Oauth2 app:
https://example.com/oauthcallback#access_token=ACCESS_TOKEN&token_type=Bearer&expires_in=3600
but cant seem to access it, i could only see response.status which is 200, response.header, ect.. how to get the url ?
Response Schema of axios request
{
// `data` is the response that was provided by the server
data: {},
}
try this
response.data.url
You can parse your request's response url like this:
response.request.responseURL
so im dispatching an action after login and using a getter to retrieve credential information that is used to initiate another fetch request. the request is going to the server correctly, and the getter is returning the appropriate data, however req.query on the server just returns [object Object]. this is the code:
getter in component:
created () {
this.$store.dispatch('user/setFriends', {email: this.userInfo.email})
},
computed: {
...mapGetters('user', {
userInfo: 'user_info'
})
}
actions:
async setFriends ({
commit
}, email) {
try {
let request = new Request(`http://localhost:3000/users?id=${encodeURIComponent(email)}`)
await fetch(request)
await (r => r.data)
await (r => commit('setFriends', r))
} catch (error) {
console.error(error.r)
}
}
route handler
router.get('/', function (req, res, next) {
console.log(req.query.id)
});
other attempt at fetch request
var url = new URL('http://localhost:3000/users')
var params = {
id: email
}
url.search = new URLSearchParams(params)
await fetch(url)
i also read this link Setting query string using Fetch GET request when consulting how to write query strings with fetch. any help would be appreciated, thanks
the problem here is that the payload when dispatching the action does not need to be passed as an object, instead of passing of
created () {
this.$store.dispatch('user/setFriends', {email: this.userInfo.email})
},
simply the value
created () {
this.$store.dispatch('user/setFriends', this.userInfo.email)
},