res redirect node js

How do I redirect in expressjs while passing some context?

I am using express to make a web app in node.js. This is a simplification of what I have:

My problem is the following:

If I find that the data sent in /category doesn’t validate, I would like pass some additional context to the / page. How could I do this? Redirect doesn’t seem to allow any kind of extra parameter.

res redirect node js. Смотреть фото res redirect node js. Смотреть картинку res redirect node js. Картинка про res redirect node js. Фото res redirect node js

9 Answers 9

There are a few ways of passing data around to different routes. The most correct answer is, of course, query strings. You’ll need to ensure that the values are properly encodeURIComponent and decodeURIComponent.

For more dynamic way you can use the url core module to generate the query string for you:

So if you want to redirect all req query string variables you can simply do

And if you are using Node >= 7.x you can also use the querystring core module

Another way of doing it is by setting something up in the session. You can read how to set it up here, but to set and access variables is something like this:

And later on after the redirect.

Hopefully that will give you a general idea how to pass information around in an Express application.

The easiest way I have found to pass data between routeHandlers to use next() no need to mess with redirect or sessions. Optionally you could just call your homeCtrl(req,res) instead of next() and just pass the req and res

I had to find another solution because none of the provided solutions actually met my requirements, for the following reasons:

req.session: You may not want to use req.session because you need the express-session dependency for this, which includes setting up a session store (such as MongoDB), which you may not need at all, or maybe you are already using a custom session store solution.

next(): You may not want to use next() or next(«router») because this essentially just renders your new page under the original URL, it’s not really a redirect to the new URL, more like a forward/rewrite, which may not be acceptable.

So this is my fourth solution that doesn’t suffer from any of the previous issues. Basically it involves using a temporary cookie, for which you will have to first install cookie-parser. Obviously this means it will only work where cookies are enabled, and with a limited amount of data.

Источник

res.redirect(‘back’) with parameters

7 Answers 7

Using the referer header to find what page your user came from might be helpful:

You might also want to store backURL in req.session, if you need it to persist across multiple routes. Remember to test for the existence of that variable, something like: res.redirect(req.session.backURL || ‘/’)

The most important difference is using an explicit ‘bounce’ parameter in the query string that overrides the Referer url.

res redirect node js. Смотреть фото res redirect node js. Смотреть картинку res redirect node js. Картинка про res redirect node js. Фото res redirect node js

A really easy way of implementing this is to use connect-flash, a middleware for express that leverages the session middleware built into express to pass ‘flash’ messages to the next request.

It means you don’t need to add fields to track urls or messages to the form or route patterns for your views.

It provides a simple version of the same feature in Ruby on Rails.

(obviously you have to be using the Express framework for this to use, but I highly recommend that too!)

Plug it in like this:

And then use it like this:

If you’re using sessions, you can just add that reg_error object to the req.session object before your redirect. Then it will be available on the req.session object when you’re loading the previous page.

You could simply have it redirect as res.redirect(‘. error=1’)

then you can simply pull the error on the appropriate page by doing a:

you can hardcode in several different error values and have it respond appropriately depending on what error occurred

Note that this makes your webpage susceptible to manipulation since users can type in their own parameters and get your page to respond to it, so make sure the action you take is not something you wouldn’t want people abusing. (Should be fine for simple error displaying)

Источник

How to redirect to another page in node.js [duplicate]

I would also like to know, how to redirect a user on button click.

Let’s say I’m on display user page, where I display all of my users, then there is «add another used button». How do i do that? How do I redirect user to Register.js page after onclick?

res redirect node js. Смотреть фото res redirect node js. Смотреть картинку res redirect node js. Картинка про res redirect node js. Фото res redirect node js

6 Answers 6

You should return the line that redirects

Ok, I’ll try to help you using one my examples. First of all, you need to know I am using express for my application directory structure and for creating files like app.js in an automatically way. My login.html looks like:

The important thing here is action=»/login». This is the path I use in my index.js (for navigating between the views) which look like this:

This allows me to redirect to another page after a succesful login. There is a helpful tutorial you could check out for redirecting between pages:

To read a statement like let’s have a look at a simple profile.html which has the following structure:

To get the the attributes of the user variable, you have to initialize a user variable in your routing.js (called index.js in my case). This looks like

I am using mongoose for my object model:

Ask me anytime for further questions. Best regards, Nazar

Источник

Node.js редирект (перенаправление страницы) — Koa.js & Express.js

res redirect node js. Смотреть фото res redirect node js. Смотреть картинку res redirect node js. Картинка про res redirect node js. Фото res redirect node js

May 18, 2019 · 3 min read

Привет! В этой статье я помогу вам разобраться с редиректом на Node.js на примерах применения плагинов для Koa.js, а также Express.js.

Кроме этого, будет рассмотрена реализация редиректа для проектов, которые хостятся на Heroku.

Стандартные возможности редиректа в Koa.js & Express.js

Мы имеем стандартные функции редиректа из коробки нашего Node.js фреймворка для перенаправления с одного роута на другой.

Для Koa.js: ctx.redirect(url)

Для Express.js: res.redirect(url)

Самописная middleware-функция для редиректа с Express.js

Использование готовых плагинов

HTTPS редирект в Koa.JS

Для того, чтобы реализовать HTTPS редирект, я использовал плагин koa-sslify. Это middleware-функция, которая совершает автоматическое перенаправление на HTTPS запрашеваемого URL с 301 HTTP кодом (Moved Permanently).

Для проектов без Heroku

Для проектов на Heroku

Также, ес л и у вашего сайта несколько доменов, стоит явно указать свойство hostname в объекте опций, который мы передаём в sslify middleware-функцию, с нужным вам доменом, чтобы редирект происходил на нужный вам host. В таком случае, инициализация нашей middleware выглядит так:

HTTPS редирект в Express.js

Для реализации перенаправления на HTTPS с Express.js, мною также будет использован подход внедрения middleware-прослойки в наш сервер.

Для проектов без Heroku

Если вы также хотите и редирект для вашего localhost сервера, то нужно передать флаг ‘true’ первым аргументом при вызове нашего ssl middleware следующим образом:

Для проектов на Heroku

“www”-редирект с Koa.js

Для реализации этого редиректа можно, опять же, написать собственноручный скрипт в несколько строчек, либо воспользоваться уже готовой, лаконичной реализацией middleware-прослойки. Рассмотрим плагин на примере koa-www-force.

Редирект на URL с www для всех роутов:

Редирект на URL без www для всех роутов:

Источник

Automatic HTTPS connection/redirect with node.js/express

I’ve been trying to get HTTPS set up with a node.js project I’m working on. I’ve essentially followed the node.js documentation for this example:

as expected. But if I do

In retrospect this seems obvious that it would work this way, but at the same time, people who eventually visit my project aren’t going to type in https://yadayada, and I want all traffic to be https from the moment they hit the site.

How can I get node (and Express as that is the framework I’m using) to hand off all incoming traffic to https, regardless of whether or not it was specified? I haven’t been able to find any documentation that has addressed this. Or is it just assumed that in a production environment, node has something that sits in front of it (e.g. nginx) that handles this kind of redirection?

This is my first foray into web development, so please forgive my ignorance if this is something obvious.

21 Answers 21

Ryan, thanks for pointing me in the right direction. I fleshed out your answer (2nd paragraph) a little bit with some code and it works. In this scenario these code snippets are put in my express app:

The https express server listens ATM on 3000. I set up these iptables rules so that node doesn’t have to run as root:

All together, this works exactly as I wanted it to.

To prevent theft of cookies over HTTP, see this answer (from the comments) or use this code:

If secure, requests via https, otherwise redirects to https

res redirect node js. Смотреть фото res redirect node js. Смотреть картинку res redirect node js. Картинка про res redirect node js. Фото res redirect node js

If you follow conventional ports since HTTP tries port 80 by default and HTTPS tries port 443 by default you can simply have two server’s on the same machine: Here’s the code:

With Nginx you can take advantage of the «x-forwarded-proto» header:

As of 0.4.12 we have no real clean way of listening for HTTP & HTTPS on the same port using Node’s HTTP/HTTPS servers.

Some people have solved this issue by having having Node’s HTTPS server (this works with Express.js as well) listen to 443 (or some other port) and also have a small http server bind to 80 and redirect users to the secure port.

If you absolutely have to be able to handle both protocols on a single port then you need to put nginx, lighttpd, apache, or some other web server on that port and have act as a reverse proxy for Node.

I use the solution proposed by Basarat but I also need to overwrite the port because I used to have 2 different ports for HTTP and HTTPS protocols.

I prefer also to use not standard port so to start nodejs without root privileges. I like 8080 and 8443 because I came from lots of years of programming on tomcat.

My complete file become

Then I use iptable for forwording 80 and 443 traffic on my HTTP and HTTPS ports.

res redirect node js. Смотреть фото res redirect node js. Смотреть картинку res redirect node js. Картинка про res redirect node js. Фото res redirect node js

You can use the express-force-https module:

res redirect node js. Смотреть фото res redirect node js. Смотреть картинку res redirect node js. Картинка про res redirect node js. Фото res redirect node js

I find req.protocol works when I am using express (have not tested without but I suspect it works). using current node 0.10.22 with express 3.4.3

This answer needs to be updated to work with Express 4.0. Here is how I got the separate http server to work:

res redirect node js. Смотреть фото res redirect node js. Смотреть картинку res redirect node js. Картинка про res redirect node js. Фото res redirect node js

If your app is behind a trusted proxy (e.g. an AWS ELB or a correctly configured nginx), this code should work:

res redirect node js. Смотреть фото res redirect node js. Смотреть картинку res redirect node js. Картинка про res redirect node js. Фото res redirect node js

Most answers here suggest to use the req.headers.host header.

The Host header is required by HTTP 1.1, but it is actually optional since the header might not be actually sent by a HTTP client, and node/express will accept this request.

You might ask: which HTTP client (e.g: browser) can send a request missing that header? The HTTP protocol is very trivial. You can craft a HTTP request in few lines of code, to not send a host header, and if each time you receive a malformed request you throw an exception, and depending on how you handle such exceptions, this can take your server down.

So always validate all input. This is not paranoia, I have received requests lacking the host header in my service.

Also, never treat URLs as strings. Use the node url module to modify specific parts of a string. Treating URLs as strings can be exploited in many many many ways. Don’t do it.

Источник

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *