如何使用 node.js (express) 处理 get 请求 [英] How to handle a get request with node.js (express)

查看:27
本文介绍了如何使用 node.js (express) 处理 get 请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是一个 node.js 新手,我正在用它创建我的第一个大型应用程序(我正在使用 express).当用户使用 get 请求加载 id 时,我需要让我的网页执行一些 javascript 画布绘制,例如

I'm a node.js newbie and I'm creating my first big app with it (I'm using express). I need to have my webpage perform some javascript canvas-drawing when the user loads an id with a get request, e.g.

www.mywebsite.com/page?id=22

我知道我可以用一个简单的方法来处理这个问题

I know I can handle this with a simple

var express        =        require("express");
var app            =        express();
app.get('handle',function(request,response){
    //request.id
});

但我不知道如何使用该 ID 的要求绘图启动我的网页.互联网上关于 express 和 get 的每个教程都解释了如何处理 get 请求……这个问题是关于接下来会发生什么?"

but I don't know how to start my webpage with the asked drawing for that id. Every tutorial on the internet on express and get explains how to handle get requests... well this question is about "what happens next?"

改写:我不知道我应该如何告诉 html 页面您需要绘制与此 ID 关联的内容",然后将该页面发送回用户.>

Rephrased: I'm not sure how should I tell the html page "you need to draw what is associated with this id" from express and then send that page back to the user.

推荐答案

您可以从 params 获取 id ,然后根据该 id 返回响应.

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));
});

注意事项:

  1. 您使用 /page/:id 来制作类似 www.mywebsite.com/page/22www.mywebsite.com/的网址page?id=22 并且您可以使用 request.params.id(输出:22)访问服务器上的 id.

  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).

使用response,您可以write 对服务器的响应.在这个例子中,我返回了一个 json 对象.

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

writeHead 200 中来自 status 表示 OK ,而 content-type 表示我返回一个 json 对象

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

你可以返回你想要的东西,一个页面或其他东西,这只是一个例子(PoC).

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

这篇关于如何使用 node.js (express) 处理 get 请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆