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

查看:125
本文介绍了如何使用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的图形启动我的网页。互联网上的每个教程都可以快速的获得解释如何处理获取请求...这个问题是关于接下来会发生什么?

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页面你需要从express中绘制与该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 / 22 www.mywebsite.com/page?id=22 ,您可以使用 request.params.id (输出:22)

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

使用回复您可以写入对服务器的响应。在这个例子中,我返回aj子对象。

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

writeHead strong> 200 来自确定的状态,而 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天全站免登陆