Get token from URL and send to post api with Axios Vuejs - javascript

Hi i need to take token from URL http://192.168.178.25:8080/register?token=eyJhbGciOiJIUzI...
and send a Post request on API for confermation account
I have tried this but on backend i've receive SyntaxError!
Someone can help me?
<script>
import axios from 'axios'
export default {
name: 'Register',
data() {
return {
confirmation : false,
somethingWrong: false
}
},
created: function() {
axios.post('/api/users/validateRegister', null,{
params: {
registerToken: this.$route.query.token,
state: this.$route.query.state
}
})
.then((res) => {
console.log(res)
this.confirmation = true
})
.catch((err) => {
console.log(err)
this.somethingWrong = true
})
}
}
</script>

Your server is expecting JSON but you are sending something else.
Try running this in your browser console (devtools): JSON.parse('asdasd').
How you are sending it right now:
axios.post('/api/users/validateRegister', null,{
params: {
registerToken: this.$route.query.token,
state: this.$route.query.state
}
})
Will send a request that looks like:
/api/users/validateRegister?registerToken=<token>&state=<state>
To do a POST request with body according to docs, you do:
axios.post(url[, data[, config]])
Which in your case means, assuming you need registerToken and state as part of body and not query parameters:
axios.post('/api/users/validateRegister',{
registerToken: this.$route.query.token,
state: this.$route.query.state
})
Notice how there's no null in the 2nd param and no params: {}
You can also according to docs do the following syntax:
axios({
method: 'post'
url: '/api/users/validateRegister',
data: {
registerToken: this.$route.query.token,
state: this.$route.query.state
}
})

It looks like your server is throwing an error when trying to parse the body.
From your axios request, you're passing parameters instead of a body - you can see this by looking at the URL in the POST error on the right-hand side of your screenshot.
Instead, send the payload in the body like this;
axios.post('/api/users/validateRegister',
{
registerToken: this.$route.query.token,
state: this.$route.query.state
})
As you haven't provided any of the server-side code there may be something else going on we can't see.

Related

Axios get call in Vue3 not working, although curl and javascript work as expected

I'm trying to make an API call from my Vue3 app. The prepared API has an endpoint like http://localhost:8888/api/dtconfigsearch, where one needs to pass a json payload like { "Modelname": "MyFancyModel"} to get the full dataset with the given modelname. Pure get functions without a payload / a body do work from my Vue3 project to the golang backend, but I'm having problems with passing a payload to the backend.
Test with curl -> ok
$ curl -XGET localhost:8888/api/dtconfigsearch -d '{"Modelname" : "MyFancyModel" }'
{"ID":4,"Modelname":"MyFancyModel","ModelId":"96ee6e80-8d4a-b59a-3524-ced3187ce7144000","OutputTopic":"json/fancyoutput"}
$
This is the expected output.
Test with javascript ok
Source file index.js:
const axios = require('axios');
function makeGetRequest() {
axios.get(
'http://localhost:8888/api/dtconfigsearch',
{
data: { Modelname : "MyFancyModel" },
headers: {
'Content-type' : 'application/json'
}
}
)
.then(resp => {
console.log(resp.data)
})
.catch(err => {
console.log(err)
})
}
makeGetRequest()
Output
$ node index.js
{
ID: 4,
Modelname: 'MyFancyModel',
ModelId: '96ee6e80-8d4a-b59a-3524-ced3187ce7144000',
OutputTopic: 'json/fancyoutput'
}
$
Here, I also get the desired output.
Test within Vue fails :-(
Source in the Vue one file component:
onSelection(event) {
let searchPattern = { Modelname : event.target.value }
console.log(event.target.value)
console.log("searchPattern = " + searchPattern)
axios.get("http://localhost:8888/api/dtconfigsearch",
{
data : { Modelname : "Windshield"},
headers: {
'Content-type' : 'application/json',
'Access-Control-Allow-Origin': '*'
}
})
.then(response => {
console.log(response.data)
})
.catch(err => {
console.log(err)
alert("Model with name " + event.target.value + " not found in database")
})
},
Output in browser:
In the image you can see in the terminal log on the right side that the backend is not receiving the body of the API call. However, in the browser information of the call there is content in the config.data part of the object tree, which is the payload / the body. The only thing that bothers me that it is not a json object, but stringified json, although it was entered as json object. According to the documentation, the parameter name (data) in the call should be correct to hold the body content of the api call.
I've tried different header information, looked if it could be a CORS issue, what it isn't to my opinion, exchanged key data with body, used axios instead of axios.get and adapted parameter, all without success. The version of the axios library is 0.27, identical for Vue and vanilla javascript. After checking successfully in javascript, I was sure that it would work the same way in Vue, but it didn't.
Now I'm lost and have no further ideas how to make it work. Maybe someone of you had similar issues and could give me a hint? I'd be very grateful for some tipps!!

React Admin parseResponse doesn't trigger when query returns error

I'm using React Admin and ra-data-graphQl, when I update something in my UserEdit component all works perfect, BUT, when I need to handle the error message from the API, I don't know where catch it.
This is my Update query:
case 'UPDATE': {
const updateParams = { ...params };
return {
query: gql`mutation updateUser($id: ID!, $data: UpdateUser!) {
data: updateUser(id: $id,input:$data) {
${buildFieldsGraphQL(updateFields)}
}
}`,
variables: {
...updateParams,
id: updateParams.data.uuid,
data: {
...updateParams.data,
},
},
parseResponse: (response) => {
console.log('tr response: ', response);
},
};
}
When the API returns an error, it never reach the console.log.
I was searching a list with options here (https://github.com/marmelab/react-admin/tree/master/packages/ra-data-graphql#options) searching something like "parseError", but I did not find nothing similar.
I need to catch the error and show a message in the UserEdit form.
Reading the link that I share in this post, it say this:
but must return an object matching the options of the ApolloClient query method with an additional parseResponse function.
I understand that I should go to the link in the word "query" and check if there is something like "parserError", but the link is broken:
https://www.apollographql.com/docs/react/reference/index.html#ApolloClient.query
Any help?
Ok, its easier. By adding the onFailure function I can handle the error.

How to get JSON in Laravel from vue.js axios POST?

I have some problem with receiving JSON data from vuex with axios in my Laravel Backend.
I have vuex store like this, and I want to send it to backend on click.
order: {
delivery_id: null,
user_id: null,
is_active: true,
bill: null,
name: null,
surname: null,
father_name: null,
phone: null,
payment_type: 'cash',
delay: null,
cashback_paid: null,
card: null,
payment_screenshot: null,
cart: null,
}
In vue component I have this method:
sendOrder() {
let order = this.$store.state.order.order;
console.log(order)
axios
.post('/api/products', order, {
header: {
'Content-Type': 'application/json'
}
})
.then((response) => {
console.log(response);
})
.catch((error) => {
console.log(error);
})
}
And this is my pretty simple Laravel Controller:
$test = json_decode($request->getContent(), true);
$test = $test['payment_type'];
return response($test);
But when I'm doing this POST request, I'm receiving empty data in response.
Also, I've tried to check my API with Postman, and it's working fine. I just send request, then go to F12 > Network > find my request and copy Request Payload source data. Then I've pasted it into Postman body (raw, json) and make request with this data to same url (http://localhost:8000/api/orders), and its return 'cash' as expected. So I decided, that it's vue.js or axios problem, but I have no idea how to fix that. Thank you!
UPDATED
I already have tried to remove Content-Type from axios, JSON.stringify order and had the same result - empty data on response.
I think, before you use order in axios you should stringify the JSON data:
let order = JSON.stringify(this.$store.state.order.order);
Second part of the answer after some comments:
Are you sure about the routes file? I would call the controller from the web.php file (same folder) with a declared function (for example mytest), like this:
Route::post('/api/products', 'ProductController#mytest');
and put your controller logic in that function:
public function mytest()
{
$test = json_decode($request->getContent(), true);
$test = $test['payment_type'];
return response($test);
}
If that doesn't work (also in combination with JSON.stringify), my only idea is a typo in your "pretty simple Laravel Controller" ;)...

react and axios POST throws an Uncaught (in promise) TypeError: parsed is undefined

I'm baffled what I'm doing wrong in my code. The GET call gets resolved, but when I try to do a POST call to the same server I get an error. My POST endpoint works fine with Postman.
apiConnection.js
function get(data){
return axios.get("http://localhost:8080/api/questions",
{
params:data.payload
}, {
headers: {
'accept': 'application/json',
}
})
}
function post(data){
console.log(data.payload) //my payload is received here
return axios.post("http://localhost:8080/api/answer", {
params:data.payload
}, {
headers: {
'accept': 'application/json',
}
}
)
}
export { get, post }
Here is the error I get in the console
And here is how I make the call in react
index.js
GET (Receives response normally)
import { get, post } from "apiConnection.js"
...
componentDidMount(){
const data = {
payload: {
linkId: getSlug()
}
}
get(data).then((result) => {
this.setState({reportId: result.data.report.id});
})
}
POST (Throws error)
vote(userVote){
const data = {
payload: {
reportId: this.state.reportId,
}
}
post(data).then((result)=>{
this.state.questions[this.state.currentQuestion].vote = userVote
});
}
I have found the culprit of the issue but if someone can add more information about it, it might be helpful for others.
In my question, for brevity, I changed the request URL from imported constants to hardcoded links.
In my code, I have a variable for both GET and POST
return axios.post(apiEndpoints[data.ep], data.payload)
I import the endpoint variables like so
import * as apiEndpoints from './apiEndpoints';
apiEndpoints.js
const server = 'http://localhost:8080/'
const api_version = 'api/'
const base_url = server+api_version;
export const EP_QUESTIONS = base_url+'questions';
export const EP_ANSWER = base_url+'answer';
For some unknown reason EP_ANSWER throws the error even though I'm not making a typo when I define data.ep (data.ep has EP_ANSWER, which
I checked a million times)
The solution was to just change EP_ANSWER to EP_ANS and everything worked as expected.
No idea why this is the case. It might be some global variable or a reserved word.
Just came across this and noted #Ando's response.
So, knowing that I first tried a hard coded URL, it worked.
I then successfully did url.toString() and it worked.
Not sure why but Javascript seems to treat a an object string differently than a true string.

How to send JSON data correctly using Axios to a rails server, to match the required rails params hash correctly?

I am making a GET request to a rails server, and the parameter should look like:
{"where"=>{"producer_id"=>["7"]}
I am making the request from the frontend application which is in Vue, and using Axios for making the request. I am making the request like this:
const data = await this.axios.get('http://localhost:3000/data.json', {
headers: {
'X-User-Token': this.$store.getters.authToken,
'X-User-Username': this.$store.getters.user.username
},
params: {
where: {
producer_id: data.producers
}
}
})
However, in the rails server output it shows that the params were sent like this:
{"where"=>"{\"producer_id\":[\"7\"]}"}
And I don't get the correct data back because of it.
How can I solve this? Why is the second level in params (the where object) being sent as a string?
Turns out that in this case the params have to be serialized https://github.com/axios/axios/issues/738
I used the paramsSerializer function as well to get over this
const data = await this.axios.get('http://localhost:3000/data.json', {
headers: {
'X-User-Token': this.$store.getters.authToken,
'X-User-Username': this.$store.getters.user.username
},
params: {
where: {
producer_id: data.producers
}
},
paramsSerializer: function (params) {
return jQuery.param(params)
}
})
EDIT:
I am now using qs instead of jQuery:
axios.defaults.paramsSerializer = (params) => {
return qs.stringify(params, {arrayFormat: 'brackets'})
}

Categories

Resources