How to send data with redirect back in Express JS - node.js

Hello I am new to NodeJs. Currently I am working in node with Express framework.
I installed the express-back package in my project and now I want to send send back data to view from where post request fired.
Below is my code that I write:
routes.js
router.post('/register/user',Rules.UserRules.registerUser,UserController.registerUser)
UserController.js
const {check, validationResult} = require('express-validator');
registerUser = function (req, res, next) {
// Validate request parameters, queries using express-validator
const errors = validationResult(req)
console.log("==== errors ===")
console.log(errors.array())
if (!errors.isEmpty()) {
console.log("==== erorror founded ====")
return res.redirect('/signup',{errors:errors})
}else{
console.log('--- form body ----')
console.log(req.body)
}
}
module.exports = {registerUser}
When I submit my form to this route then control moves to UserController and I validations fails then I want to send it back to view without defining the redirect path I just want to send it back to view from where request received with errors. But I did not find any useful solution yet.
Is there any idea that how I can achieve this target. Suggest any useful link for nodejs beginner.

use res.send(errors) it send errors to client at this route. but if you want to redirect it to another route and then send it to client you have to create /signup route and use res.send(errors) it send errors to client. by default ``` res```` will redirect to redirected route.
router.post('/signup', (req, res)=>{
//send error or do somethings.
res.json(req.body.errors);
})

Use
app.locals.errors=errors
to make your error variable available to your template upon redirection as a general guide. Read more at http://expressjs.com/en/5x/api.html#app.locals. Remember, this will share the error variable across the application, so do not forget to apply logic that allows only the logged in user to view the error information relevant to that user.

Related

Access URL query Params in an Express POST route

I have a NodeJS/Express application.
From an url endpoint titled: localhost:3000/form?someProp=someValue&somethingElse=someOtherValue
This page submits a form to another Express endpoint.
I submit to an Express POST endpoint. I know in a GET endpoint I could access the query params via req.query, but I cannot seem to do that in a POST request.
Is there a way to access the query params from the request in a POST route?
(other than splicing the header.referrer... which I may just have to do)
Here are some code snippets:
If I submit to the first route it works, if I submit to the second... it does not.
router.get('/test',
(req, res) => {
console.log(req.query); // {someProp: someValue, somethingElse: someOtherValue }
}
);
router.post('/test2',
(req, res) => {
console.log(req.query); // returns {}
}
);
So I tried to send a simple request to test it and got everything working without doing anything special (The only thing extra I have is that I'm using body-parser middleware from npm):
app.use(bodyParser.json({limit: '50mb'}));
Then I tried this simple route and got the result query params as you can see in the picture attached.
http://localhost:8080/test?test=1&what=2
Any chance you're sending the other form request from the client in a different way? try looking at the network in chrome and see if you sending what you expecting. Obviously, there is something missing here as it worked for me without doing anything special.

Validate http headers for authentication in every page using nuxt.js

I am trying to validate every HTTP request to the nuxt server for authorization.
In this official tutorial,
it requires me to add a validate function in every page, which seems not to work for me, as I'm seeking a way to write a middleware that validates all requests to the nuxt server.
And so, I found nuxt's middleware support, but the official document is really unfriendly, I can't understand at all.
What I'm expecting is a plugin-like module that allows me to put my middleware into nuxt.
Just like what can be achievable in Express (as following).
export default function (req, res, next)
So that I can easily validate headers per request to nuxt.
How can I achieve this? Thank you very much.
Go to your directory middleware/ and create an auth.js
The first argument is your context. Context contains alot of things like your store, app, route, redirect, and it also contains req
You can check out what context has in it: https://nuxtjs.org/api/context/
export default function ({ req, res, redirect }) {
let authenticated = false;
if(!authenticated) {
redirect("/login")
}
}
You can go now to on of your page, and add this to your export default {}
middleware: ["auth"]
Now if you try to access the page you should be redirected to login
I believe Nuxt Middleware is what you need.
In middleware/auth.js
// write any custom validation functions
export default function (context) {
context.userAgent = process.server
? context.req.headers['user-agent']
: navigator.userAgent
}
then in nuxt.config.js
// this will register the middleware functions above for every route
export default {
router: {
middleware: 'auth'
}
}

External web service redirects the user and posts data to my callback URL. How do I render the posted data to the user in an Express/Next.js app?

Any help would be hugely appreciated! Been stuck on this for a few days.
I have an Express/Next.js app where:
I send the user to an external website
user makes a payment
external website redirects and posts data back to my callback URL.
So now I have the user on a mysite.com/payment-complete route but also want to display the data that was sent back.
I have an app.post endpoint to successfully grab the data:
app.post("/payment-complete", async (req, res) => {
const transactionID = req.body.trans_id;
});
How would I pass the data to the user who is already on that route? Or pass the data before the page is rendered?
The flow of data is third party > my server > user and I'm not sure how to make this work.
I'd be grateful for any help/direction with this.
If anyone comes across this - the problem was that in Express (and other languages) you can't redirect or render a view for an AJAX POST request but you can if the POST request is coming from a submitted html form. The web service was in fact POST-ing the data and redirecting my users with a form and so I could render a view.
Following code worked using Handlebars templating engine to send the render.
router.post("/payment-ok", async (req, res) => {
const transactionID = req.body.trans_id;
return res.render("rendertest", { id: transactionID });
});
Should also possibly work with app.render to send a Next.js view instead, but I wanted to render from a separate routes file.

ExpressJS : res.redirect() not working as expected?

I've been struggling for 2 days on this one, googled and stackoverflowed all I could, but I can't work it out.
I'm building a simple node app (+Express + Mongoose) with a login page that redirects to the home page. Here's my server JS code :
app
.get('/', (req, res) => {
console.log("Here we are : root");
return res.sendfile(__dirname + '/index.html');
})
.get('/login', (req, res) => {
console.log("Here we are : '/login'");
return res.sendfile(__dirname + '/login.html');
})
.post('/credentials', (req, res) => {
console.log("Here we are : '/credentials'");
// Some Mongoose / DB validations
return res.redirect('/');
});
The login page makes a POST request to /credentials, where posted data is verified. This works. I can see "Here we are : '/credentials'" in the Node console.
Then comes the issue : the res.redirect doesn't work properly. I know that it does reach the '/' route, because :
I can see "Here we are : root" in the Node console
The index.html page is being sent back to the browser as a reponse, but not displayed in the window.
Chrome inspector shows the POST request response, I CAN see the HTML code being sent to the browser in the inspector, but the URL remains /login and the login page is still being displayed on screen.
(Edit) The redirection is in Mongoose's callback function, it's not synchronous (as NodeJS should be). I have just removed Mongoose validation stuff for clarity.
I have tried adding res.end(), doesn't work
I have tried
req.method = 'get';
res.redirect('/');
and
res.writeHead(302, {location: '/'});
res.end();
Doesn't work
What am I doing wrong? How can I actually leave the '/login' page, redirect the browser to '/' and display the HTML code that it received?
Thanks a million for your help in advance :)
The problem might not lie with the backend, but with the frontend. If you are using AJAX to send the POST request, it is specifically designed to not change your url.
Use window.location.href after AJAX's request has completed (in the .done()) to update the URL with the desired path, or use JQuery: $('body').replaceWith(data) when you receive the HTML back from the request.
If you are using an asynchronous request to backend and then redirecting in backend, it will redirect in backend (i.e. it will create a new get request to that URL), but won't change the URL in front end.
To make it work you need to:
use window.location.href = "/url"
change your async request (in front end) to simple anchor tag (<a></a>)
It's almost certain that you are making an async call to check Mongoose but you haven't structured the code so that the redirect only happens after the async call returns a result.
In javascript, the POST would look like something this:
function validateCredentials(user, callback){
// takes whatever you need to validate the visitor as `user`
// uses the `callback` when the results return from Mongoose
}
app.post('/credentials', function(req, res){
console.log("Here was are: '/credentials'";
validateCredentials(userdata, function(err, data){
if (err) {
// handle error and redirect to credentials,
// display an error page, or whatever you want to do here...
}
// if no error, redirect
res.redirect('/');
};
};
You can also see questions like Async call in node.js vs. mongoose for parallel/related problems...
I've been working on implementing nodemailer into my NextJS app with Express. Was having this issue and came across this. I had event.preventDefault() in my function that was firing the form to submit and that was preventing the redirect as well, I took it off and it was redirecting accordingly.
Add the following in your get / route :
res.setHeader("Content-Type", "text/html")
Your browser will render file instead of downloading it

express authentication middleware failing to redirect correctly after a PUT request [duplicate]

This question already has answers here:
Express js - can't redirect
(4 answers)
Closed 9 years ago.
I'm using passportjs with a middleware below. It is suppose to check if the user is login when he requests certain things. If he is not signed in, he should be redirected to the login page.
I have a request route as follows:
app.put('/fantasyteams/:fantasyTeamId', auth.requiresLogin, fantasyteams.update);
This route will be called when the user tries to update a resource called Fantasy Team in the website
auth.requiresLogin is a middleware as follows:
exports.requiresLogin = function (req, res, next) {
if (req.isAuthenticated()) {
return next()
}
return res.redirect("/signin");
};
After logging in my user, I simulated session expiry by deleting the session cookie. Thereafter thru the website I made a PUT '/fantasyteams/123' request to update fantasy team number 123.
fantasyteams.update is simply a mongodb / mongoose save operation:
exports.update = function(req, res){
var fantasyteam = req.fantasyteam;
fantasyteam = _.extend(fantasyteam, req.body);
fantasyteam.save(function(err){
res.jsonp(fantasyteam);
});
};
As expected, the route handler (app.put ... ) above caught the request, pass it to the auth.requiresLogin middleware to check if the user is logged in. So it turns out the user isn't logged in since I deleted his session cookie. res.redirect is called as expected. However, the website doesn't redirect to the sign in page. I see this in the node.js command logs:
PUT /signin 404 328ms
What did I do wrong?
Looks like the problem is you don't have a route handler for PUT /signin. The original request was a put, so when it redirects it's still part of that same 'put' request from the browser. Just add a handler for put/post/whatever with app.all('/signin')

Resources