New axios request in response - vue.js

I'm posting to an API using axios, and using the data from the response I want to make another API request but I'm running into issues saying that axios is not defined.
The calls, that are in inside my Vue login component, are the following:
this.axios({
method: 'post',
url: '/my_api/test',
data: "testdata=test123",
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
})
.then(function (response) {
this.axios({
method: 'get',
url: '/my_api/test2',
data: "testdata2=" + response.data.id
})
})
and as I mentioned earlier, the error in my console is the following: TypeError: Cannot read property 'axios' of undefined.
I´ve tried writing the second request without this. but I'm having the same issues. Where am I going wrong?

You have to use an arrow function here.
Regular functions have their own this value.
this.axios({
method: 'post',
url: '/my_api/test',
data: "testdata=test123",
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
})
.then(response => {
this.axios({
method: 'get',
url: '/my_api/test2',
data: "testdata2=" + response.data.id
})
})
Or if you prefer old-fashioned way you can save this reference to some variable to have access to it in the callback:
const self = this
this.axios({
method: 'post',
url: '/my_api/test',
data: "testdata=test123",
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
})
.then(function (response) {
self.axios({
method: 'get',
url: '/my_api/test2',
data: "testdata2=" + response.data.id
})
})

Related

I can't access response body Cypress Api Testing

I want to automate the api using Cypress, but I can't access the response body.
Use this path cy.log(JSON.stringify(response.body.payload[0]
Api Response
Code
context('GET /Auth', () => {
it('should return a list with all products', () => {
cy.request({
method: 'GET',
url: 'https://auth.plus.a101.com.tr/api/homepage/punch-cards/20149126',
headers: {
'Authorization' : 'Bearer ' + access_token
}
})
.then((response) => {
expect(response.status).to.eq(200)
cy.log(JSON.stringify(response.body.payload[0]))
});
});
});
I get error
You have to convert your response object a json string and then parse it. Instead you can try the following:
cy.request({
method: 'GET',
url: 'https://auth.plus.a101.com.tr/api/homepage/punch-cards/20149126',
headers: {
'Authorization' : 'Bearer ' + access_token
}
}).then((response) => {
response = JSON.stringify(response)
var jsonData = JSON.parse(response)
cy.log(response.body.payload[0])
});

Error in API response saying required parameters React native

When I call API I am getting below error in response. please find below is code and error message.
TEST RESPONSE:
{
"responseData": {"limit": ["Limit is required"],
"module_type": ["Module type required"],
"section": ["section value \"liveability || investment || recommend\" is required"],
"skip": ["Skip is required"]
}
Implemented code:
fetch( 'https://api.dotcomkart.com/api/homePagePropertyList?', {
method: 'POST',
body: JSON.stringify({
skip: 0,
limit: 10,
module_type:'buy',
section: 'liveability'
}),
})
Try this way
import FormData from 'FormData';
...
var data = new FormData();
data.append("skip", "0");
data.append("module_type", "buy");
....
fetch('YOUR_URL', {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'multipart/form-data',
},
body: data,
})
.then((response) => response.json())
.then((responseJson) => {
console.log('response object:',responseJson)
})
.catch((error) => {
console.error(error);
});
Sometimes when you work with REST API call you have to work with correct headers.
In your case I suppose your are missing two important headers required to activate a good communication between client and servers:
accept
content-type
Please review your code based on this one:
fetch('https://api.dotcomkart.com/api/homePagePropertyList?', {
method: 'POST',
headers: {
"accept": "application/json",
"content-type": "application/json"
},
body: JSON.stringify({
skip: 0,
limit: 10,
module_type:'buy',
section: 'liveability'
}),
})
I think the server is returning "missing" parameters because is not able to understand the type of content. With Content-Type you should be able to instruct the server on how to parse your data.

Axios formData dont send any data

I want to upload a file using Axios but for that I need to use formData, my problem is that when I am using formData the data are not send at all.
Here is my code without formData, its working fine all the data are sent :
axios({
method: 'post',
url: jsonurl,
data: {
session_id: '123',
},
headers: {
'Content-Type': 'multipart/form-data',
}
})
.then((value) => {
console.log(value); // return in console : status 200 and config: data: session_id: "123" ...
})
.catch(err=>console.error(err));
Same code with formData (no data sent, $_GET['id'] doesnt exist) :
const formData = new FormData();
formData.append('session_id', '123');
axios({
method: 'post',
url: jsonurl,
formData,
headers: {
'Content-Type': 'multipart/form-data',
}
})
.then((value) => {
console.log(value); // return in console : status 200 but config: data: FormData {}
})
.catch(err=>console.error(err));
No data sent, return in console status 200 but config: data: FormData {} (so no data) and on backend $_POST['session_id'] doesnt exist, the form is sent (I get my jsonencode return) but there is no input data.
I dont catch any error either.
Finally I found the solution, my syntax was wrong, here is one who works :
var postResults = await axios.post(jsonurl,
formData,
{
headers: {
'Content-Type': 'multipart/form-data'
}
}
)
.then(function(value){
console.log(value);
return value;
})
.catch(function(error){
console.log(error);
});

Vuejs: axios; Passing custom header in POST method

We are making an axios POST call from VueJs, need to pass a custom header. The way it is coded now, the custom header is not getting passed to the server script, other headers are getting passed. Please let me know what I might be doing wrong. Appreciate your help.
axios({
method: 'post',
url: urltocall,
data: strjson,
config: {
headers: {
'Access-Control-Allow-Origin': 'http://localhost:1337',
'Accept': 'application/json',
'Content-Type': 'application/json',
'username': 'test1'
}
}
})
.then(function (response) {
}
The headers object should not be put into a "config" object.
It's just...
axios({
method: 'post',
url: urltocall,
{
headers: {
....
Try doing it like this:
axios
.post(urltocall, myDataAsJSON, {
headers: {
"Access-Control-Allow-Origin": "http://localhost:1337",
"Accept": "application/json",
"Content-Type": "application/json",
"username": "test1"
}
})
.then(response => {
console.log("Success: " + response.data);
})
.catch(error => {
console.log("Error: " + error.response.data);
});
By the way, based on your 'Content-Type': 'application/json',, I know you're trying to send a JSON object, but where/what is this object?
Also, refer to the Full documentation for more information.

How to get access token from api in react native

I am using react native and i want to get the access token from api which is created in django using oAuth 2 authentication
i am passing all the details which are required but i do not know why i am getting error of unsupported grant type
fetch('MyApiUrl', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/x-www-form-urlencoded',
},
body: JSON.stringify({
'grant_type': 'password',
'username': 'MyUserNameSettedInApi',
'password': 'PasswordSettedInApi',
'client_id': 'MyClientId',
'client_secret': 'MyClientSecret',
'scope': 'read Write'
})
})
.then((response) => response) <----tried response.json() but giving same error of grant type
.then((responseData) => {
console.log(responseData);
})
My expected result is i want access token should display
and what i am getting is
Response {type: "default", status: 400, ok: false, statusText: undefined, headers: Headers, …}
headers: Headers {map: {…}}
ok: false
status: 400
statusText: undefined
type: "default"
url: "http://MyUrl"
_bodyInit: "{"error": "unsupported_grant_type"}"
_bodyText: "{"error": "unsupported_grant_type"}"
__proto__: Object
please help
thanks in advance
tried response.json() but giving same error of grant type - this is answer from Your oauth server.
response.json() transform your response data into json decoded string.
Change Your code to this:
let formData = new FormData();
formData.append('grant_type', 'password');
formData.append('username', 'MyUserNameSettedInApi');
formData.append('password', 'PasswordSettedInApi');
formData.append('client_id', 'MyClientId');
formData.append('client_secret', 'MyClientSecret');
formData.append('scope', 'read Write');
fetch('MyApiUrl', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/x-www-form-urlencoded',
},
body: formData
})
.then((response) => response.json())
.then((responseData) => {
console.log(responseData);
});
Install qs library
npm install qs
Import it in your app and then you'll be able to send it.
Use qs.stringify as shown below
fetch('http://localhost:8888/o/token',
{
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/x-www-form-urlencoded;'
},
body: qs.stringify({
'grant_type': 'password',
'username': 'MyUserNameSettedInApi',
'password': 'PasswordSettedInApi',
'client_id': 'MyClientId',
'client_secret': 'MyClientSecret',
})
})
I also got that same issue of "{"error": "unsupported_grant_type"}" for that, I just pass all the body parameters directly without using JSON.stringify({}); It works for me, find the example code below.
body: 'grant_type=password&username=MyUserName&password=MyPassword'
you need to update the body section only.
fetch('MyApiUrl', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
body: 'grant_type=password&username=MyUserName&password=MyPassword'
})
.then(res => res.json())
.then(token => console.log(token))
.catch(err => console.error(err));
Hope this will help you.