axios will not send request body data to my express server? - javascript

I am using axios to do AJAX calls to my Express web server. Whenever I make a post request and pass in a piece of data, the data is for some reason never sent to the server. Whenever I check the request.body, no data is ever there even though I clearly added it.
<script>
axios.post("/api/users", {
firstname: 'fred'
})
.then(function(res){
console.log(res.data);
})
.catch(function(err){
console.log(err);
})
</script>
The above is the AJAX Post request I am making with axios. As you can see, I passed in a piece of data: "firstname" to be sent to "/api/users".
app.post("/api/users", function(req, res){
console.log(req.body);
res.send({newData: req.body.firstname});
});
This is my very simple post route that it is sending to. I am simply passing the data that I sent back to the client. Whenever this runs, "firstname" is never found. When I check the console.log, the req.body is empty, and the .then console.log on the client side only shows some random "_proto_" object, but not what I sent. I've done exactly as the documentation says, why isn't "firstname" going through??
EDIT: I just tried with fetch, it still didn't work. It seems like any AJAX request is just not working right, the data doesn't go through.

Related

Process multiple unique Express JS requests

I've got a small Express JS api that I'm building to handle and process multiple incoming requests from the browser and am having some trouble figuring out the best approach to handle them.
The use case is that there's a form, with potentially up-to 30 or so people submitting form data to the Express JS api at any given time, the API then POSTS this data of to some place using axios, and each one needs to return a response back to the browser of the person that submitted the data, my endpoint so far is:
app.post('/api/process', (req, res) => {
if (!req.body) {
res.status(400).send({ code: 400, success: false, message: "No data was submitted" })
return
}
const application = req.body.Application
axios.post('https://example.com/api/endpoint', application)
.then(response => {
res.status(200).send({ code: 200, success: true, message: response })
})
.catch(error => {
res.status(200).send({ code: 200, success: false, message: error })
});
})
If John and James submit form data from different browsers to my Express JS api, which is forwarded to another api, I need the respective responses to go back to the respective browsers...
Let's make clear for you, A response of a request will only send to the requester, But if you need to send a process request and send a response like, hey i received your request and you can use another get route to get the result sometimes later, then you need to determine which job you mean. So You can generate a UUID when server receives a process request and send it back to the sender as response, Hey i received your process request, you can check the result of process sometimes later and this UUID is your reference code. Then you need to pass the UUID code as GETparam or query param and server send you the correct result.
This is the usual way when you are usinf WebSockettoo. send a process req to server and server sends back a reference UUID code, sometime later server sends the process result to websocket of requester and says Hey this is the result of that process with that UUID reference code.
I hope i said clear enough.

Problem with React making Get request to Node(express)

As the title says, i have a part of my react app that tries to get some data from my database, making a select based on the value I passed to it. So im gonna go ahead and first show the code where i think the problem lies:
So first, this is the function from one of my forms that sends the request to the server, i know code is probably ugly, but i can tell from the console.logs that the parameters im sending are what i intend to send(a string called "licenciaInput"
async handleClickLicencia (event) {
event.preventDefault();
console.log(this.state);
console.log("licenciaInput: "+this.state.licenciaInput);
const datoBuscar = this.state.licenciaInput;
axios.get('http://localhost:3001/atletas/:licencia',this.state)
.then(response =>{
console.log(response)
})
.catch(error =>{
console.log(error)
})
And then, i have this function which is called in that localhost route which attempts to get "licencia", and launch a select in my postgresql db where licencia="whatever", you can see the sentence in the code:
const getAtletasByLicencia = (request, response) => {
const licencia = request.body.licenciaInput;
console.log("Request: "+request);
console.log("what the server gets: "+licencia);
// const licencia = request.licenciaInput;
const sentencia ="SELECT * FROM atleta WHERE licencia ='"+licencia+"'";
pool.query(sentencia, (error, results) =>{
if(error){
throw error
}
response.status(200).json(results.rows)
})
}
As you can see, i have console.logs everywhere, and i still cannot access whatever element i send, because i always get on the server console "undefined" value.
TLDR:How can i access the "licenciaInput" i passed from my client form to my server, i have tried request.body.licenciaInput, request.params.licenciaInput, and request.licenciaInput, but none of those seem to work
I also know i have to treat after that the data i receive from the server, but i need to solve this before looking two steps ahead. Im also really new to React and node/express, so feel free to burn me with good practices im not meeting.Thanks in advance
EDIT: Im also adding this code that i have which shows the route for my method in the server:
app.get('/atletas/:licencia', db.getAtletasByLicencia)
As #Gillespie59 suggested that i should send a POST request, but i dont think i should if im both trying to send a parameter to the server to make a select, and then send the results back to the client
Change your request to:
axios.get(`http://localhost:3001/atletas/${this.state.licenciaInput}`)
...
and your route (if you are using express) should look like this:
app.get('/atletas/:licencia', function (req, res) {
var licencia = req.params.licencia
...
})
As you are using request.body you should send a POST request with axios and add a body.

How to send a JSON response and redirect to some html page after success in Node.js using express?

I am trying to send a JSON response, and redirect the page at the same time. It is not happening. Is there any way to redirect in Express.js while sending some JSON response to client? I want to use this JSON response to render the value to the redirected HTML page.
My Code -
//I tried using the below code. But it is not working
const app = express();
app.get('/user', authenticationMiddleware, (req,res) => {
res.send({name : "StackOverFlow", reason : "Need help!"});
res.redirect('/user/me');
})
Expected result :
I should get the {name : "StackOverFlow", reason : "Need help!"} as response (I will use fetch() to get the response) in the redirected client side HTML.
What you'll want to do is setup your response object to look something like the below:
res.send({name : "StackOverFlow", reason : "Need help!", redirect_path: "/user/me"});
And then in the function callback on your client (where you're making the fetch request), you'll want to pickup the value of response.redirect_path and pass it into a JS redirect method.
You could use something like:
location.href = response.redirect_path
Example usage (on the client-side)
fetch("http://yousite.com/endPoint")
.then((resp) => resp.json()) // Transform the data into json
.then(function(response) {
if (response.redirect_path) { //optional check to see if a redirect path exists
location.href = redirect_path;
}
})
})
Bear in mind, I'm assuming that the argument passed in your fetch response callback function is called 'response', if it is 'res' or something else, you'll have to adjust the code above accordingly.
You should send json response to client side and under success function of your ajax call use window.open(redirecturl)
Let me know if it didn't help

re-render pug view with express

Basically what I wantto achieve is a searchable/filterable listview
so far I'm able to fetch some data from a database and have express with pug render me a page showing the results in a listview.
Now I want to add the functionality of filtering the displayed listview.
Therefore on every keyup event within a textbox I make an AJAX post request to the server sending the query string from the textbox. So far everything works just fine, but when i try to "re-render" the page with the filtered resultset nothing happens in the browser.
My routes look like this:
var rechnungen;
router.get('/', function(req, res) {
connection.query('SELECT * FROM rechnungen ', function(err, result) {
rechnugen = result;
res.render('rechnungen', {rechnungen: result});
});
router.post('/:query', function(req, res) {
console.log("received ajax request");
console.log("with query " + req.params.query);
res.render('rechnungen', {rechnungen: {}});
});
initially the query statement fetches the data and res.render works just fine, when I make the AJAX call everything seems to work as well (the console log output matches my input) but regardless what i try to pass to the view (res.render) in the post route nothing happens.
Is it not possible to "re-render" a view or is there any other conceptional misstake I make?
thanks for your help
AJAX POST call is not a traditional HTTP call.
The rendered page sent from the server will come in the response object of success handler of your AJAX call.
So, either
replace whole HTML with the response HTML, or
make a traditional HTTP form POST, in that case the browser by-default renders the response of the server.

callback function req. and res

I'm having trouble to understand why my callback function needs 2 parameters, i.e. one for the request and one for the response?
For instance i bind a callback function to my server:
server.on("request", doThis(req, resp));
In my opinion he needs only one parameter (req for example here) to store the req information (GET, POST, url, etc.). Why does he need a second for response? I write the information in resp. (i.e. the server, so my other scripts) and not the client.
Every time a request is coming in, the callback function is invoked and so the req parameter is set. Am i wrong? But why do I need the response parameter? My server needs it when he is responding but not when I'm reading/saving the request informations?
The Response parameter is what's generally used to send back a response.
A request comes in, you get the request's data in the req (first) param and you then use the res (second) param to send back a response like:
server.on('message', function(req, res){
res.send('hello your ip is: ' + req.client.ip);
})
This is all dependant on your framework but in expressjs this is how it works (more or less).
To answer your question, you don't need it - you can simply not issue it as a parameter (although it will still be accessible) if you don't plan on responding (which is weird and quite uncommon)
server.on('message', function(req){
console.log('someone requested "message"')
})
Generally speaking, you would always send back a response although the end user might never visually see it, it's just to confirm that the action has been completed successfully.
server.on('save', function(req, res){
saveFile(req.file)
res.sendStatus(200)
})
Additionally, you could check if the process completed successfully - if it did you'd send back a success message, otherwise send back an error message.
server.on('save', function(req, res){
saveFile(req.file, function(error){
if(error) res.sendStatus(500)
res.sendStatus(200)
})
})

Categories