I am new to using Axios and struggling to display anything from a response function. I'm mainly interested to see see at least the response status. The only output I can see is when there is a 4xx code returned, but nothing when the call is successful.
Below is my code, any help would be appreciated:
setServiceGroupPromise(){
//Read data from ./data/sourcingRules.txt
let filePath = './data/sourcingRules.txt';
var fileData = fs.readFileSync(filePath, 'utf8');
console.log(fileData);
let postURL = `${siteConfig}`;
const config = {
method: 'post',
url: postURL,
params: {
'apiKey': process.env.SHIPPING_SERVICE_API_KEY
},
headers: {
'content-type': 'application/xml',
},
data: fileData
};
console.log(`Post request going to: ${postURL}`);
axios(config)
.then(function (response) {
console.log(response.data);
console.log(response.status);
})
.catch(function (error) {
console.log('The following error occurred : ' + error.message);
});
}
If you are not seeing anything from the console.log(response.data), try logging something like console.log({response}), or console.log('show me something', response.data)
I am having problems using 'nested' Fetch calls within a React Native function. It seems the first Fetch works correctly, however an error is thrown on the second. Here is the code:
//****CALL TWO FETCH REQUESTS...
const data = { passkey: '12345', callup: 'name' };
const secondary = { passkey: '12345', callup: 'name' };
fetch('https://myremoteserveraddress', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(data),
})
.then(function(response) {
if (response.ok) {
return response.json();
} else {
return Promise.reject(response);
}
})
.then(data => {
// Store the post data to a variable
_post = data;
console.log('Success on FIRST FETCH:', data);
console.log('answer is:', data.answer);
console.log('answer is:', _post.answer);
// Fetch another API
fetch('https://myremoteserveraddress', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(secondary),
})
})
.then(function (response) {
if (response.ok) {
return response.json();
} else {
return Promise.reject(response);
}
})
.then(function (userData) {
console.log('Returned from BOTH fetch calls'); //does not write to console
console.log(_post, userData); //does not write to console
this.vb.start();
})
.catch((error) => {
console.error('Error in onPressPublishBtn:', error);
});
//****
It seems the second Fetch call returns 'undefined', despite being identical to the first Fetch call which seems to work successfully. The error returned is "TypeError: undefined is not an object (evaluating 'response.ok')". If anybody can advise on what the problem may be I would be greatly appreciative. Thank you in advance.
You should return a Promise from the second then(...) block so that the response is passed to the third then(...) block. You might want to try something like this:
// Fetch another API
return fetch('https://myremoteserveraddress', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(secondary),
})
I am trying to communicate with an API from my React application using Axios. I managed to get the GET request working, but now I need a POST one.
I need the body to be raw text, as I will write an MDX query in it. Here is the part where I make the request:
axios.post(baseUrl + 'applications/' + appName + '/dataexport/plantypes' + plan,
{
headers: { 'Authorization': 'Basic xxxxxxxxxxxxxxxxxxx',
'Content-Type' : 'text/plain' }
}).then((response) => {
this.setState({data:response.data});
console.log(this.state.data);
});
Here I added the content type part. But how can I add the body part?
Thank you.
Edit:
Here is a screenshot of the working Postman request
How about using direct axios API?
axios({
method: 'post',
url: baseUrl + 'applications/' + appName + '/dataexport/plantypes' + plan,
headers: {},
data: {
foo: 'bar', // This is the body part
}
});
Source: axios api
You can use postman to generate code. Look at this image. Follow step1 and step 2.
If your endpoint just accepts data that have been sent with Body (in postman), You should send FormData.
var formdata = new FormData();
//add three variable to form
formdata.append("imdbid", "1234");
formdata.append("token", "d48a3c54948b4c4edd9207151ff1c7a3");
formdata.append("rate", "4");
let res = await axios.post("/api/save_rate", formdata);
You can use the below for passing the raw text.
axios.post(
baseUrl + 'applications/' + appName + '/dataexport/plantypes' + plan,
body,
{
headers: {
'Authorization': 'Basic xxxxxxxxxxxxxxxxxxx',
'Content-Type' : 'text/plain'
}
}
).then(response => {
this.setState({data:response.data});
console.log(this.state.data);
});
Just have your raw text within body or pass it directly within quotes as 'raw text to be sent' in place of body.
The signature of the axios post is axios.post(url[, data[, config]]), so the data is where you pass your request body.
The key is to use "Content-Type": "text/plain" as mentioned by #MadhuBhat.
axios.post(path, code, { headers: { "Content-Type": "text/plain" } }).then(response => {
console.log(response);
});
A thing to note if you use .NET is that a raw string to a controller will return 415 Unsupported Media Type. To get around this you need to encapsulate the raw string in hyphens like this and send it as "Content-Type": "application/json":
axios.post(path, "\"" + code + "\"", { headers: { "Content-Type": "application/json" } }).then(response => {
console.log(response);
});
C# Controller:
[HttpPost]
public async Task<ActionResult<string>> Post([FromBody] string code)
{
return Ok(code);
}
https://weblog.west-wind.com/posts/2017/sep/14/accepting-raw-request-body-content-in-aspnet-core-api-controllers
You can also make a POST with query params if that helps:
.post(`/mails/users/sendVerificationMail`, null, { params: {
mail,
firstname
}})
.then(response => response.status)
.catch(err => console.warn(err));
This will POST an empty body with the two query params:
POST
http://localhost:8000/api/mails/users/sendVerificationMail?mail=lol%40lol.com&firstname=myFirstName
Source: https://stackoverflow.com/a/53501339/3850405
Here is my solution:
axios({
method: "POST",
url: "https://URL.com/api/services/fetchQuizList",
headers: {
"x-access-key": data,
"x-access-token": token,
},
data: {
quiz_name: quizname,
},
})
.then(res => {
console.log("res", res.data.message);
})
.catch(err => {
console.log("error in request", err);
});
This should help
You can pass the params like so
await axios.post(URL, {
key:value //Second param will be your body
},
{
headers: {
Authorization: ``,
'Content-Type': 'application/json'
}
this makes it easier to test/mock in Jest as well
I got same problem. So I looked into the axios document.
I found it. you can do it like this. this is easiest way. and super simple.
https://www.npmjs.com/package/axios#using-applicationx-www-form-urlencoded-format
var params = new URLSearchParams();
params.append('param1', 'value1');
params.append('param2', 'value2');
axios.post('/foo', params);
You can use .then,.catch.
For sending form data in the body, you can just format the data in url params like this 'grant_type=client_credentials&client_id=12345&client_secret=678910' and attached it to data in the config for axios.
axios.request({
method: 'post',
url: 'http://www.example.com/',
data: 'grant_type=client_credentials&client_id=12345&client_secret=678910',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
})
The only solution I found that would work is the transformRequest property which allows you to override the extra data prep axios does before sending off the request.
axios.request({
method: 'post',
url: 'http://foo.bar/',
data: {},
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
transformRequest: [(data, header) => {
data = 'grant_type=client_credentials'
return data
}]
})
This worked fine for me when trying to send authentication credential in body in raw json format.
let credentials = {
username: "your-username",
password: "your-password",
};
axios
.get(url, { data: credentials })
.then((res) => {
console.log(res.data);
})
Used in React js
let url = `${process.env.REACT_APP_API}/validuser`;
let body = JSON.stringify({
loginid: "admin",
password: "admin",
});
var authOptions = {
method: "post",
url: url,
data: body,
headers: {
"Content-Type": "application/json",
},
json: true,
};
axios(authOptions)
.then((resp) => {
console.log("response :- ",resp);
})
.catch((error) => {
alert(error);
});
axios({
method: 'post', //put
url: url,
headers: {'Authorization': 'Bearer'+token},
data: {
firstName: 'Keshav', // This is the body part
lastName: 'Gera'
}
});
There many methods to send raw data with a post request. I personally like this one.
const url = "your url"
const data = {key: value}
const headers = {
"Content-Type": "application/json"
}
axios.post(url, data, headers)
let url='<your domain.extension>';
let data= JSON.stringify('mydata');
axios
.get(url, { data })
.then((res) => {
console.log(res.data);
})
For me this solution works, i.e. JSON.stringify(your data) , just convert your raw data using JSON.stringify method.
I hope this works.
If not using vanilla js I have always used jQuery to make AJAX requests. Now since React has been taking over, to make AJAX requests there is no need to use the whole jQuery library to make these requests so we are encouraged to use either js' built in fetch method, axios or many others.
I have been trying to make a POST request using fetch. I am able to make it using axis but not fetch.
axios.post('https://reqres.in/api/login', {
"email": "peter#klaven",
"password": "cityslicka"
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
The axios code looks like this, but when I try what I believe to be the same thing using fetch it doesn't work. Can anyone see what I am missing? The values are being posted, but the API is returning an error, so I must be doing something wrong.
var data = {
"email": "peter#klaven",
"password": "cityslicka"
}
fetch("https://reqres.in/api/login", {
method: "POST",
body: JSON.stringify(data)
})
.then(function(response){
return response.json();
})
.then(function(data){
console.log(data)
});
var headers = {
"Content-Type": "application/json",
"Access-Control-Origin": "*"
}
try adding the above lines to headers.
var data = {
"email": "peter#klaven",
"password": "cityslicka"
}
fetch("https://reqres.in/api/login", {
method: "POST",
headers: headers,
body: JSON.stringify(data)
})
.then(function(response){
return response.json();
})
.then(function(data){
console.log(data)
});
Using arrow functions:
fetch('http://myapi.com/user/login', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-type': 'application/json',
},
body: JSON.stringify({
login: login,
senha: password
})
}).then(response => response.json())
.then((responseJson) => console.log(responseJson))
}).catch(error => console.log(error));
I'm trying to get some datas from an external API (from Mashape) that requires a specific header to set the API key.
Everything is ok using jQuery :
$.ajax({
url: 'https://omgvamp-hearthstone-v1.p.mashape.com/cardbacks',
type: 'GET',
data: {},
dataType: 'json',
success: function(data) { console.dir((data.source)); },
error: function(err) { alert(err); },
beforeSend: function(xhr) {
xhr.setRequestHeader("X-Mashape-Authorization", "MY_API_KEY");
}
});
However, when I'm trying to do the same request with axios for a react application, I have a 404 error:
axios.get({
url: 'https://omgvamp-hearthstone-v1.p.mashape.com/cardbacks',
headers: {
"X-Mashape-Authorization": "MY_API_KEY"
}
})
Is there something I'm missing ? Thanks.
I finally understood.
We need to set the header BEFORE the request using axios.defaults.headers.common['header_name'] = "API_KEY"; :
axios.defaults.baseURL = 'https://omgvamp-hearthstone-v1.p.mashape.com';
axios.defaults.headers.common['X-Mashape-Key'] = "API_KEY";
axios.get('/cardbacks')
.then((resp) => {
console.dir(resp);
});
Try also to do it like this without setting defaults:
axios.get('https://omgvamp-hearthstone-v1.p.mashape.com/cardbacks', {
headers: { "X-Mashape-Key": "MY_API_KEY" }
})
.then((resp) => {
console.dir(resp);
})
.catch(err => {
console.log(err);
});
}
It should work.
PS I also observed that you use different header keys in question(X-Mashape-Authorization) and answer(X-Mashape-Key). Maybe that is also somehow related to 404 error?
I got better way to solve this .
You just need add parameters format from axios like this below:
axios({
method: <method>,
url: <url>,
data: <params>,
headers: { common: <headers> },
})
.then(response => {
if (!cb) return { error: 'No callback' };
return cb(response);
})
.catch((err) => cb(err.response));