简体   繁体   中英

res.redirect is not a function in express

I'm currently trying to redirect to an external site with node and express specifically in a get call. However, I can't seem to find a possible solution. Any help would be appreciated. Note that when trying response.redirect I'm getting TypeError: res.redirect is not a function. However, when I view the express documentation it seems to be in there.

    app.get('/:urlToForward', (res, req, next)=>{
    //Stores the value of param
//     var shorterUrl = res.params.urlToForward;
// shortUrl.findOne({'shorterUrl': shorterUrl}, (err,data)=>{
// //  if (err) {
// //             res.send("This shorterUurl does not exist.");
// //         }
// //         else {
// //             res.redirect(301, data.originalUrl);
// //         }
// //         response.end();
// });

res.redirect('https://www.google.com');
});

You can do res.redirect('http://app.example.io');

Express docs: http://expressjs.com/api.html#res.redirect

Just use simple:

app is instance of invoked Express application.

    app.get('/', function(request,respond) {
      respond.redirect('your_url'); //Pass between the brackets your URL.
    });

Order matters in the arguments. req must be first, then res, then next.

app.get('/:urlToForward', (req, res, next)=>{ ...

Note you can use ES6 shorthand for shorterUrl, no need to type it out twice.

 app.get('/:urlToForward', (req, res, next)=> {
        //Stores the value of param
        var shorterUrl = res.params.urlToForward;
        shortUrl.findOne({shorterUrl}, (err, data)=> {
            if (err) {
                res.send("This shorterUrl does not exist.");
            }
            else {
                res.redirect(data.originalUrl);
            }
            response.end();
        })
    });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM