POST request with axios ReactJS - reactjs

I'm new to HTTP requests and trying to do POST request of my form submitting with axios and getting an error 400. I want to send my data to url and it should be seen there in JSON format.
codesandbox https://codesandbox.io/s/fast-brook-g3488?file=/src/App.js

Error is very clear you are not passing data to axios post method.I am not sure what kind of validation you have in server but it will be look like this
axios({
method: "post",
url: "https://frosty-wood-6558.getsandbox.com:443/dishes",
headers: { "Content-Type": "application/json" },
data:{
name:event.name,
preparation_time:event.preparation_time,
type:event.type,
spiciness_scale:event.spiciness_scale,
}
})
.then(function (response) {
console.log(response);
})
.catch(function (response) {
console.log(response);
});
Since its now throwing error preparation time validation. Not sure what's the validation you have in server side
preparation_time: "Wrong format"

Related

can i send form-data with axios with delete request in react?

i need send this request with axios.
i need header as multipart request, like below
headers: {
"Content-type": "multipart/form-data",
},
I used spring boot for backend. It expect maltipart not application/json. I tried below code, But it not worked for multipart.
axios.delete(URL, {
headers: {
Authorization: authorizationToken
},
data: {
source: source
}
});
Thanks a lot #Sinan Yaman. I generated it using POSTMAN. Answer is
var axios = require('axios');
var FormData = require('form-data');
var data = new FormData();
data.append('keyName', 'project/photoes/1613388881570-note1.txt');
var config = {
method: 'delete',
url: 'localhost:8080/storage/deleteFile',
headers: {
...data.getHeaders()
},
data : data
};
axios(config)
.then(function (response) {
console.log(JSON.stringify(response.data));
})
.catch(function (error) {
console.log(error);
});
Typically before make frontend we test our backend with postman. For any type of frontend http calls code can automatically generate using postman. This is awesome feature of POSTMAN. Follow below steps.
Press the code button
Select the your backend code environment

Post request in redux-saga not working, nothing seems to happen

I would like to make post request in redux-saga. My code looks like:
var formdata = new FormData();
formdata.append("points", "a,b");
formdata.append("pid", "someid");
formdata.append("tions", "cses");
formdata.append("exp", "cx");
const ans = yield call(fetch,
'http://localhost:8000/api',
{
method: "POST",
headers: { 'Authorization': 'Token tokenid',
"Content-Type": "application/json",},
body : formdata
});
In Postman it is working fine (selected form-data in body), but in saga, the POST request is not happening at all.
Please suggest where I am doing wrong?
The problem is with your Exceptions on server-side, When you are throwing an error the headers are not set. So what you should do is with CORS Errors only with 400 bad request react fetch request.
Update :- The 400 Bad request has gone away after I added "Content-Type": "application/x-www-form-urlencoded" in the headers and changed the body type accordingly
Example :-
fetch("api/xxx", {
body: "email=test#example.com&password=pw",
headers: {
"Content-Type": "application/x-www-form-urlencoded",
},
method: "post",
}

$http - post - Bad request error not handled (undefined)

I am trying to do a POST to create an account and I am expecting a 400 Bad Request (Username already used or Email already used).
I have confirmed with other tools (RESTED for firefox) that I am receiving the correct 400 Error with my message, but with AngularJS response.status, response.data and response.statusText all give an 'undefined' value.
Below is the definition of my request in AngularJS:
var req = {
method: 'POST',
url: myURL,
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
},
data: $scope.user
};
$http(req).then(
function(response){
console.log("account created perfectly!");
},
function(response){
console.log("ERROR " + response.status + ": account cannot be created!");
// the data is Username/Password
alert(response.data + " invalid!");
}
)
What am I doing wrong?
Can you post your inspector screenshot here?
Looks like there is some issue with the passing of request body.
The 4xx error comes when the client sends a bad request.
Also, for your use case, return status code 2xx as this is the valid business case and it should not be 4xX.

Response is undefined in success $http call angularJS

Although my backend is working correctly and I'm getting correct response from Postman crafted request
I can't see response in my angularJS controller. ( i execute this call inside controller to simplify situation )
$scope.click = function (auction_id) {
$http({
url: baseUrl + 'auctions/' + auction_id +'/followers',
headers: {
'Content-Type' : 'application/vnd.api+json'
},
method: 'POST'
})
.then(function(response) {
console.log(response);
})
.catch(function(response) {
return response;
});
};
I'm passing token with httpInterceptor which is working fine for the rest of my app.
URL is correct because I'm getting valid error number in console:
POST ##################/v1/auctions/172/followers
422 (Unprocessable Entity)
CategoryCtrl.js:64 undefined
64 line is that one console log in success .then(function....
Headers in (which I believe is) response headers from postman tab (third from Body in first screenshot)
Why response is undefined?
*Hashes in url code are mine.
From your REST API request, you're getting response with status 422, that means you've got a client error. Regarding your request, you have to handle a request when error will come. To handle error in asynchronous requests there is a second parameter of .then(mySuccessMethod(), myMethodOnError()) method.
More details about .then() and .catch() methods for promisses.
$scope.click = function (auction_id) {
$http({
url: baseUrl + 'auctions/' + auction_id +'/followers',
headers: {
'Content-Type' : 'application/vnd.api+json'
},
method: 'POST'
})
.then(function(response) {
console.log(response);
}, function(error) {
// Here goes your code to handle an error with status 4XX
console.log(error)
})
.catch(function(response) {
// Catch will come when you throw an error
return response;
});
};
When you made the request in Postman, you pass the token in the Auth attribute of the header in the request. In your code, you did not.

Nodejs sending external API POST request

i am trying to send a POST request from my angularjs controller to the nodejs server which should then send a full POST request to the external API and this way avoid CORS request as well as make it more secure as i'm sending relatively private data in this POST request.
My angularjs controller function for making the post request to the nodejs server looks like this and it works fine:
var noteData = {
"id":accountNumber,
"notes":[
{
"lId":707414,
"oId":1369944,
"nId":4154191,
"price":23.84
}
]
}
var req = {
method: 'POST',
url: '/note',
data: noteData
}
$http(req).then(function(data){
console.log(data);
});
Now the problem lies in my nodejs server where i just can't seem to figure out how to properly send a POST request with custom headers and pass a JSON data variable..
i've trierd using the nodejs https function since the url i need to access is an https one and not http ,i've also tried the request function with no luck.
I know that the url and data i'm sending is correct since when i plug them into Postman it returns what i expect it to return.
Here are my different attempts on nodejs server:
The data from angularjs request is parsed and retrieved correctly using body-parser
Attempt Using Request:
app.post('/buyNote', function (req, res) {
var options = {
url: 'https://api.lendingclub.com/api/investor/v1/accounts/' + accountNumber + '/trades/buy/',
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': apiKey
},
data = JSON.stringify(req.body);
};
request(options, function (error, response, body) {
if (!error) {
// Print out the response body
// console.log(body)
console.log(response.statusCode);
res.sendStatus(200);
} else {
console.log(error);
}
})
This returns status code 500 for some reason, it's sending the data wrongly and hence why the server error...
Using https
var options = {
url: 'https://api.lendingclub.com/api/investor/v1/accounts/' + accountNumber + '/trades/buy/',
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': apiKey
}
};
var data = JSON.stringify(req.body);
var req = https.request(options, (res) => {
console.log(`STATUS: ${res.statusCode}`);
console.log(`HEADERS: ${JSON.stringify(res.headers)}`);
res.setEncoding('utf8');
res.on('data', (chunk) => {
console.log(`BODY: ${chunk}`);
});
res.on('end', () => {
console.log('No more data in response.');
});
});
req.on('error', (e) => {
console.log(`problem with request: ${e.message}`);
});
req.write(data);
req.end();
Https attempt return a 301 status for some reasons...
Using the same data, headers and the url in Postman returns a successful response 200 with the data i need...
I don't understand how i can make a simple http request...
Please note: this is my first project working with nodejs and angular, i would know how to implement something like this in php or java easily, but this is boggling me..
So after a lot of messing around and trying different things i have finally found the solution that performs well and does exactly what i need without over complicating things:
Using the module called request-promise is what did the trick. Here's the code that i used for it:
const request = require('request-promise');
const options = {
method: 'POST',
uri: 'https://requestedAPIsource.com/api',
body: req.body,
json: true,
headers: {
'Content-Type': 'application/json',
'Authorization': 'bwejjr33333333333'
}
}
request(options).then(function (response){
res.status(200).json(response);
})
.catch(function (err) {
console.log(err);
})

Resources