React: axios post request with both params and body - reactjs

Currently I have an axios post request that works fine for sending the data to Spring Boot backend. But it just wraps single list of data to json and sends it as requested body:
Example:
sendAllData(data) {
return axios.post(API_URL + "receiveData", JSON.stringify(data),
{ headers: { "Content-Type": "application/json; charset=UTF-8" },
}).then(response=> console.log("repsonse", response.status)) // is 201
}
And it receives it on backend:
#RequestMapping(path = "/receiveData", method = RequestMethod.POST)
public ResponseEntity<Void> receiveData(#RequestBody Collection<ActivePOJO> activitePOJOS) {
//DO WORK WITH activePOJOS DATA
return new ResponseEntity<>(HttpStatus.CREATED);
}
However, apart from that information, I also need to send some other info like user.id (as example), so I need my backend to receive something like this:
public ResponseEntity<Void> receiveData(#RequestBody Collection<ActivitePOJO> activePOJOS, Long userID)
But I don't know which way should I prepare axios post for something like that. Should I use params instead of body?

You can use params and body together in a request with axios. To send userID as a param:
sendAllData(data) {
return axios.post(API_URL + "receiveData", JSON.stringify(data),
{ headers: { "Content-Type": "application/json; charset=UTF-8" },
params: { userID: 1 }, //Add userID as a param
}).then(response=> console.log("repsonse", response.status)) // is 201
And receive userID in controller with #RequestParam annotation:
public ResponseEntity<Void> receiveData(#RequestBody Collection<ActivitePOJO> activePOJOS, #RequestParam("userID") Long userID){
// here you can access userID value sent from axios
}

The third parameter is config and you can pass params to it along with header as a separate key. Refer this. https://github.com/axios/axios#axiosposturl-data-config
sendAllData(data) {
return axios
.post(API_URL + 'receiveData', JSON.stringify(data), {
headers: { 'Content-Type': 'application/json; charset=UTF-8' },
params: { userId: 2 },
})
.then((response) => console.log('response', response.status));
} // is 201

Related

How do I make a post request from react.js front end to flask backend that sends data but also grabs data?

I am posting a user id to the backend route /stat. In /stat I want to perform a query that takes in user id as a parameter. Then I also want to get the result of the query in the front end so I can display the value. I understand how to make a post request that successfully sends the data, but how do I program it to also grab data?
my post request on the front end looks like this:
const postData = (username) => {
try {
let result = fetch('http://127.0.0.1:5000/stat', {
credentials: 'include',
method: 'POST',
mode: 'no-cors',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
user: username
})
});
} catch(e) {
console.log(e)
}
}
and my backend route /stat looks like this:
#app.route('/stat', methods=['GET', 'POST'])
def stats():
request_data = request.get_json()
user = request_data['user']
def get_total_percent_correct(user):
correct = d.db_query('SELECT COUNT(*) FROM cards.responses WHERE guess = answer AND user_id = %s' % user)
total = d.db_query('SELECT COUNT(*) FROM cards.responses WHERE user_id = %s' % user)
return float(correct[0][0])/float(total[0][0])
response_body = {
"totalAccuracy": get_total_percent_correct(user),
"user" : user
}
return response_body
You need to get the response from the fetch call. If you send JSON from the backend this is how it would look:
fetch('http://127.0.0.1:5000/stat', {
credentials: 'include',
method: 'POST',
mode: 'no-cors',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
user: username
})
})
.then(function(response) {
console.log(response.json())
})

Spring boot doesn't recognise react fetch body

Spring boot is not getting the params in the request body.
The controller is defined like:
#PostMapping("/login")
public #ResponseBody User login(#RequestBody String username, #RequestBody String password) {
return userService.login(username,password);
}
And the fetch in React
const LogFunc = async () => {
let url = new URL("http://localhost:8080/user/login");
let params = {
username: username,
password: password
}
console.log(JSON.stringify(params));
return fetch(url, {
method: 'POST',
headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' },
body: JSON.stringify(params)
When i console.log it, it prints it like
{"username":"allanosi","password":"cap"}
which is correct but when Spring receive it, it prints:
Required request body is missing: public com.formacion.back.entities.User com.formacion.back.controllers.UserController.login(java.lang.String,java.lang.String)]
On the network part it says that it's a bad Request but I have no idea why it is.
Thanks in advance.
Can you try this? Just replace the annotation with this.
#RequestMapping(
value = "/login",
method = RequestMethod.POST,
produces = MediaType.APPLICATION_JSON_VALUE)
Another guess, spring boot is waiting string not object that's why you might getting request body is missing error. You can try this:
public #ResponseBody User login(#RequestBody Map<String, String> userData) {
// your code
}
Maybe you can try this:
const fdata = new FormData();
fdata.append('username', 'diego');
fdata.append('password', '1242342');
fetch(url, {
method: 'POST',
headers: ...,
body: fdata,
});
I had the same problemas as you and this approach has fixed my problem.

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

Http request in angular send undefine values

** It turns out that the problem was at the server **
I'm trying to excute HTTP post request (from my angular client) to my server (node express). The server recive the request but the data is undefined.
Already tried to make this req by postman and it worked perfect there.
var req = {
method: 'POST',
url: _url +'/login',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
data: { user: 'someUser', password :'somePass' }
}
$http(req)
.then(function success(res){
...
}, function error(res){
...
});
You are sending JSON data and sending the header of x-www-form-urlencoded.
Change the content type to "application/json"
Like:
headers: {
'Content-Type': 'application/json'
}

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