Node.js Problem redirecting routine post method - node.js

I write here for who can help me, since I'm new to NodeJS, I'm trying to do something simple, but in the end it doesn't work for me.
I want from the frontend, to make a request to the backend, through the ajax post method. When executing it, from the frontend send a JSON object to the backend and then from the backend it must redirect to another page to the frontend (the latter is what I could not achieve)
Example of what I try
Frontend
var objAgente = {
"FIRSTNAME": "PEDRO",
"LASTNAME": "PEREZ",
"NRORUT": "123456789",
"NROAGENT": "3",
"HRCONNECT": "12:12:12"
};
$.ajax({
type: 'POST',
url: '/LoginAgente',
data: JSON.stringify({ "objectData": objAgente}),
success: function(data) {console.log('todo OK')},
contentType: "application/json",
dataType: 'json'
});
Backend
const express = require("express");
const router = express.Router();
router.use(express.json())
router.use(express.urlencoded({ extended: true }))
router.get('/', (req, res)=>{
res.render('loading.html', { title: 'Iniciando Sistema'});
});
router.get('/Inicio', (req,res)=>{
res.render('confInitial.html', { title: 'Inicio de Sistema'});
});
router.get('/Agente', (req,res)=>{
res.render('PanelAgente/Agente.html', { title: 'Equipo solo Agente'});
});
router.post('/LoginAgente', function (req, res) {
var newUser = req.body;
console.log(newUser);
res.redirect('/Agente');
});
module.exports = router;
When I execute the sending of the JSON object to the backend, the data arrives since I can print it by console, but the res.redirect is not fulfilled;
It does not return an error, but it does not redirect me to where I want.
Thank you very much to those who can give me an idea of ​​what happens

Instead of
res.redirect('/Agente');
Try
res.send({redirect: '/Agente'});
UPDATE:
Frontend
var objAgente = {
"FIRSTNAME": "PEDRO",
"LASTNAME": "PEREZ",
"NRORUT": "123456789",
"NROAGENT": "3",
"HRCONNECT": "12:12:12"
};
$.ajax({
type: 'POST',
url: '/LoginAgente',
data: JSON.stringify({ "objectData": objAgente}),
success: function(data) {
if (data && data.redirect) {
window.location.href = data.redirect;
}
},
contentType: "application/json",
dataType: 'json'
});
Hope this helps!

as you are sending request using AJAX , server can not redirect to other page in AJAX request , you have to redirect user after you getting response from AJAX
$.ajax({
type: 'POST',
url: '/LoginAgente',
data: JSON.stringify({ "objectData": objAgente}),
success: function(data, textStatus, request){
// add redirect link here
window.location.href = '/add_link_to_redirect_here';
},
contentType: "application/json",
dataType: 'json'
});

No need to change backend code, since it may be useful in future when will need non-ajax authentication.
So simply try to get Location header from response and redirect using window.location.href
FRONTEND
var objAgente = {
"FIRSTNAME": "PEDRO",
"LASTNAME": "PEREZ",
"NRORUT": "123456789",
"NROAGENT": "3",
"HRCONNECT": "12:12:12"
};
$.ajax({
type: 'POST',
url: '/LoginAgente',
data: JSON.stringify({ "objectData": objAgente}),
success: function(data, textStatus, request){
const redirectTo = request.getResponseHeader('Location');
if (redirectTo) {
window.location.href = redirectTo;
}
},
contentType: "application/json",
dataType: 'json'
});

i think if you're trying to use and see entire body
var newUser = req.body;
console.log(newUser);
you should in your front pass the object like:
data: JSON.stringify(objAgente)
and do what you're doing:
req.body
cause if you're passing you're object into a new object he'll understand that you're gonna access these proprieties inside the obj, like:
req.body.objectData.FIRSTNAME

Related

Not Able to get request body as desired

I am working on MERN stack and I have made an api for registering users. I am using axios to send request this is what i am doing with axios inside react
const body = {
'phone': phoneData.phoneNumber, \\ phoneData is a state
'lastName': 'Flintstone'
}
await axios({
method : 'post',
url : 'http://localhost:8000/userapi/register',
data : JSON.stringify(body),
header : {'Content-Type': 'application/json'}
});
After this in NodeJS i am trying to print req.body on the console an this is what i am receiving
{ '{"phone":"7428868740","lastName":"Flintstone"}': '' }
instead of that i want req.body to store
{ phone:"7428868740",lastName:"Flintstone" }
This is my route that is getting triggered
app.post('/userapi/register', (req,res) =>{
console.log(req.body);
/* rest code to register user */
}
With Axios, you don't need to call JSON.stringify, just send the object and the server will receive it correctly.
const body = {
'phone': phoneData.phoneNumber, // phoneData is a state
'lastName': 'Flintstone'
}
await axios({
method : 'post',
url : 'http://localhost:8000/userapi/register',
data : body,
headers : {'Content-Type': 'application/json'}
});
See documentation here
On the server-side, make sure there is a middleware to parse requests in JSON format.
You can
const config = {
header: {
"Content-Type": "application/json",
},
};
const res = await axios.post(url,body,config)

Express Post method can't read property 'toString'

I have an express server with the following Post call:
app.post('/api/guitars/' , function(req, res){
const body = req.body;
//var inputGuitar = new Guitar(body.guitarMake.toString(), body.guitarModel.toString(), body.guitarSerial.toString(), body.guitarColour.toString(), body.guitarOwnerId.toString(), body.guitarYear.toString());
db.query(`INSERT INTO Guitar (GuitarMake, GuitarModel, GuitarSerial, GuitarColour, GuitarOwnerId, GuitarYear) VALUES (?, ?, ?, ?, ?, ?)`,
[body.guitarMake.toString(), body.inputGuitar.guitarModel.toString(), body.guitarSerial.toString(), body.guitarColour.toString(), body.guitarOwnerId.toString(), body.guitarYear.toString()], function(err, res){
if (err) {
console.log(err);
} else {
res.status(200).json(res);
}
});
res.end();
});
My front end code which is a React.js app is console logging this JSON object:
{"guitarMake":"Fender",
"guitarModel":"Jazzmaster",
"guitarSerial":"000000001",
"guitarColour":"Placid Blue",
"guitarOwnerId":"dummyuser",
"guitarYear":"2019"}
Which gets generated at this block:
if (isValid) {
var guitar = {
"guitarMake" : this.state.GuitarMake,
"guitarModel" : this.state.GuitarModel,
"guitarSerial" : this.state.GuitarSerial,
"guitarColour" : this.state.GuitarColour,
"guitarOwnerId" : this.state.GuitarOwnerId,
"guitarYear" : this.state.GuitarYear
}
var json = JSON.stringify(guitar);
console.log(json);
// do something..
fetch("APIGATEWAY", {
method: 'POST',
mode: 'cors',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: json,
}).then(res => {
console.log(res);
});
Everytime I send the request to the server I am getting an error saying: TypeError: Cannot read property 'toString' of undefined. When I console log the request on the backend express server it looks like this:
{ '{"guitarMake":"Fender","guitarModel":"Jazzmaster","guitarSerial":"000000001","guitarColour":"Placid Blue","guitarOwnerId":"dummyuser","guitarYear":"2019"}': '' }
I can't figure out why my request looks like this. It's only when it get sent through react app. On postman it looks normal on the server end. What am I doing wrong?
You seem to be getting the body as a string, not a json.
First, make sure you have added the json middleware to your server object:
app.use(express.json());
Second, you're using the wrong mime-type. If you intend the server to parse a json object, you should use application/json:
fetch("APIGATEWAY", {
method: 'POST',
mode: 'cors',
headers: {
'Content-Type': 'application/json', // Here!
},
body: json,
}).then(res => {
console.log(res);
});

400 Bad request while fetching data in post call

I am running my React js web app in one port 3000.
For node server I am using 4000.
While calling fetch method it returns `400 Bad request'.
Error
POST http://localhost:4006/auth/admin 400 (Bad Request)
react code npm started in 3000 port
fetch('http://localhost:4000/auth/admin',
{ mode: 'no-cors',
method: "POST",
body: JSON.stringify({
username:"admin",
password:"1234"
}),
headers: {
"Content-Type": "application/json",
'Accept': 'application/json, text/plain, */*',
credentials: "omit", //
// "Content-Type": "application/x-www-form-urlencoded",
},
})
.then((response) => console.log(response));
node code running in 4000 port
const passport = require("passport");
const route = require("../constants/routeStrings");
const keys = require("../config/keys");
const processStatus = require("../constants/processStatus");
const success = {
status: processStatus.SUCCESS
};
const failute = {
status: processStatus.FAILURE
};
module.exports = app => {
app.post('/auth/admin', passport.authenticate("local"), (req, res) => {
res.send(success);
});
};
Do not stringify the body. Change from
body: JSON.stringify({
username:"admin",
password:"1234"
}),
to
body: {
username:"admin",
password:"1234"
},
The 400 response is raised by passport since it is unable to read your params. You need to tell your "node" app to parse them before your actual routes.
// Import body parser, you should read about this on their git to understand it fully
const parser = require('body-parser');
const urlencodedParser = parser.urlencoded({extended : false});
// before your routes
app.use(parser .json());
app.use(urlencodedParser) // This will parse your body and make it available for your routes to use
Then do your other calls.
Also, make sure that you are sending username and password keys, otherwise read the documentation on how to change these key names to something else
I suffered long hours, but I overcame it throw writing those lines of code blocks. I successfully send the request to the server's controller, hopefully yours: make it try.
First define a async function to make POST request:
async function _postData(url = '', data = {}) {
const response = await fetch(url, {
method: 'POST',
mode: 'cors',
cache: 'no-cache',
credentials: 'same-origin',
redirect: 'follow',
referrerPolicy: 'no-referrer',
headers: {
"Content-type": "application/json; charset=UTF-8"
},
body: JSON.stringify(data)
});
return response.json();
}
Now create a request JSON payload:
let requestPayload = {
propertyName1: 'property value1',
propertyName2: 'property value23',
propertyName3: 'property value',
So on
}
Note: Request model will be your desired model, what request payload you actually send.
Now make a request using this payload including your end point URL:
_postData('http://servername/example', requestPayload )
.then(json => {
console.log(json) // Handle success
})
.catch(err => {
console.log(err) // Handle errors
});
100% worked on my project.

Request parameters while consuming a REST API in node.js

I would like to consume a REST service in Node.js using request.js, as follows:
var request = require('request');
request.get({
url: 'https://www.googleapis.com/storage/v1/b',
auth: {
'bearer': 'oauth2_token'
}
}, function(err, res) {
console.log(res.body);
});
However, I would like to specify also a set of request parameters, such as project, prefix, etc. (as specified at https://cloud.google.com/storage/docs/json_api/v1/buckets/list).
How can I pass these parameters in the request for consuming the API service?
You can pass in qs as the additional queries. See example below:
const queryObject = { project: 'project', prefix: 'prefix' };
request.get({
url: 'https://www.googleapis.com/storage/v1/b',
qs: queryObject,
auth: {
'bearer': "oauth2_token"
}
}, function(err, res) {
console.log(res.body);
});
See here for github issue.

The node express's bodyParser can't get the parameter in the GET request

I ajax an GET request in client side:
$.ajax({
url: '/update',
type: 'get',
data: {
"key": key,
"value": value
},
success: function (data, err) {
}
})
then at the node side, I want get the parameter
var showParam = function (req, res) {
if (req.body) {
for (var key in req.body) {
console.log(key + ": " + req.body[key]);
}
res.send({status:'ok',message:'data received'});
} else {
console.log("nothing received");
res.send({status:'nok',message:'no Tweet received'});
}
}
app.get('/update', function(req, res){
showParam(req, res);
})
The shell show the body is empty and undefined.
But when I change the get to post (both at the client side and server side), everything is ok, I can get the parameter correctly.
What's problem with my code? Do I miss something?
If you are issuing a GET request, the URL parameters are not part of the body, and thus will not be parsed by the bodyParser middleware.
To access the query parameters, just reference req.query
You can access your data for get request in server-side by using req.query.key and req.query.value.
In order to get params from bodyParser you must use POST not GET. Your ajax request and server calls must both use POST.
http://expressjs.com/api.html#req.body
app.post('/update', function(req, res){
showParam(req, res);
});
$.ajax({
url: '/update',
type: 'POST',
data: {
"key": key,
"value": value
},
success: function (data, err) {
}
});
To get the GET params, use the url module and use query = url.parse(req.url, true).query. query will contain an object with the values accessible via query.foo

Resources