How to handle a get request with node.js (express)

给你一囗甜甜゛ 提交于 2019-11-29 14:52:09

You can take the id from params and after this to return a response based on that id.

var express = require('express');
var app = express();

app.get("/page/:id",function(request, response){
    var id = request.params.id;
    // do something with id
    // send a response to user based on id
    var obj = { id : id, Content : "content " +id };

    response.writeHead(200, {"Content-Type": "application/json"});
    response.write(JSON.stringify(obj));
});

Notes:

  1. You use /page/:id to make urls like www.mywebsite.com/page/22 or www.mywebsite.com/page?id=22 and you can have acces to id on server with request.params.id (output: 22).

  2. With response you can write a response to the server. In this example i returned a json object.

  3. In writeHead 200 come from status which means OK , and content-type means that I return a json object

  4. You can return what you want, a page or something else, this is just an example (PoC).

If you want to pass multiple variables in the request, you can pass it in the following way:

var emailVar = "someEmail@gmail.com";
var nameVar = "someName";
var url = `/home?email=${emailVar}&name=${nameVar}`;
//Now make the request.

and in the backend logic, you can retrieve these values as:

app.get('/home', function(request, response)
{
    console.log(request.query.email+"  "+request.query.name);
    var email = request.query.email;
    var name = request.query.name;
    response.setHeader('Content-Type', 'application/json');
    if(request.query.email)
    {
        response.send(JSON.stringify({
            message: 'Got the email'
        }));
    }
    else
    {
        response.send(JSON.stringify({
            message: 'No email sent'
        }));
    }
});

This approach is useful for performing query operations in the backend.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!