【Node】【7】函数

函数可以作为变量传递

function execute(someFunction, value) {
  someFunction(value);
}

execute(function(word){ console.log(word) }, "Hello");

函数传递让http服务器工作,向createServer 传递了一个回调函数,该回调函数会在每次接收到 HTTP 请求时被调用,并且该回调函数会接收两个参数:requestresponse,分别代表请求和响应对象。具体来说,createServer 方法的入参是一个用于处理请求的回调函数。

var http = require("http");

// 定义 onRequest 函数,用于处理 HTTP 请求
function onRequest(request, response) {
    response.writeHead(200, { "Content-Type": "text/plain" });
    response.write("Hello World");
    response.end();
}

// 创建一个 HTTP 服务器实例,请求处理函数为onRequest
http.createServer(onRequest).listen(8888);

运行这段代码后,Node.js 服务器会在本地的 8888 端口启动。

当有请求发送到该端口时,服务器会调用 onRequest 函数来处理请求,并返回 “Hello World” 给请求方。

您可以打开一个浏览器并访问 http://localhost:8888/,这样浏览器就会发送一个 GET 请求到您的 Node.js 服务器。服务器会接收这个http请求,从而执行onRequest回调函数,并返回 “Hello World” 给浏览器,在浏览器中显示 “Hello World”。

在这里插入图片描述

要在 Node.js 服务器中处理不同的路由请求,您可以根据请求的 URL 路径来区分不同的路由,并执行相应的处理逻辑。以下是一个简单示例,演示如何在 Node.js 服务器中处理不同的路由请求:

const http = require('http');

function onRequest(request, response) {
    const { url } = request;

    if (url === '/') { 
        response.writeHead(200, { "Content-Type": "text/plain" });
        response.write("Hello World");
        response.end();
    } else if (url === '/about') {
        response.writeHead(200, { "Content-Type": "text/plain" });
        response.write("About Us Page");
        response.end();
    } else {
        response.writeHead(404, { "Content-Type": "text/plain" });
        response.write("Page Not Found");
        response.end();
    }
}

const server = http.createServer(onRequest);

server.listen(3000, 'localhost', () => {
    console.log('Server is running at http://localhost:3000/');
});

在上述示例中:

  • 当用户访问根路径 / 时,服务器返回 “Hello World”。
  • 当用户访问 /about 路径时,服务器返回 “About Us Page”。
  • 对于其他路径,服务器返回 404 Not Found。

在这里插入图片描述

上述的例子都是通过在浏览器输入请求路径,触发回调函数,写死的response。

下面给个示例:演示了如何创建一个服务器,然后在服务器端代码中发起一条 GET 请求

const http = require('http');

const onRequest = (req, res) => {
    // 发起 GET 请求
    http.get('http://www.example.com', (response) => {
        let data = '';

				// 接收到数据将数据保存
        response.on('data', (chunk) => {
            data += chunk;
        });
				
				// 结束后写到res里作为服务器的返回。
        response.on('end', () => {
            res.writeHead(200, { 'Content-Type': 'text/plain' });
            res.write('Received response from http://www.example.com: ' + data);
            res.end();
        });
    }).on('error', (err) => {
        console.error('Error during GET request:', err);
        res.writeHead(500, { 'Content-Type': 'text/plain' });
        res.write('Error during GET request');
        res.end();
    });
}


// 创建 HTTP 服务器,发起请求是调用onRequest回调函数
const server = http.createServer(onRequest);

// 启动服务器
server.listen(3000, 'localhost', () => {
    console.log('Server is running at http://localhost:3000/');
});

node 获取到post请求,想要看post请求里的body

//router.js
exports.route = function(pathname) {
    console.log("About to route a request for " + pathname);
}
//server.js
var http = require("http");
var url = require("url");

function start(route) {
  function onRequest(request, response) {
    var pathname = url.parse(request.url).pathname;
    console.log("Request for " + pathname + " received.");
    console.log("type=", request.method);

    route(pathname);

    if (request.method === "POST") {
      let body = "";

      request.on("data", (chunk) => {
        body += chunk.toString(); // 将数据块转换为字符串
      });

      request.on("end", () => {
        console.log("POST 请求的请求体:", body);
        response.writeHead(200, { "Content-Type": "text/plain" });
        response.end("Received POST data");
      });
    } else {
      response.writeHead(200, { "Content-Type": "text/plain" });
      response.write("Hello World");
      response.end();
    }
  }

  http.createServer(onRequest).listen(8888);
  console.log("Server has started.");
}

exports.start = start;

// index.js
var router = require('./router')
var server = require('./server')
server.start(router.route)
  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
Node函数架构是指用Node.js编写的云函数架构,可以用于AWS Lambda,谷歌云函数,Azure Functions等平台上运行。实现一个Node函数架构,并不难,只需遵循以下步骤: 第一步:创建项目 首先,创建一个新的Node.js项目。通过在终端中运行命令'npm init'初始化一个项目,并安装所需的依赖。如:'npm install aws-sdk'。 第二步:编写函数逻辑 编写函数逻辑并导出函数。如: exports.handler = (event, context, callback) => { // function logic const response = { statusCode: 200, body: JSON.stringify('Hello from Node function!') }; callback(null, response); }; 第三步:部署云函数 部署函数到特定云平台。AWS Lambda的部署过程,需要在AWS控制台上,创建新函数,并创建角色以授权函数访问AWS服务。然后,运行以下命令上传代码: zip -r node-lambda-function.zip ./* aws lambda create-function --function-name node-lambda-function --handler index.handler --runtime nodejs14.x --role arn:aws:iam::account-id:role/lambda-role-name --zip-file fileb://node-lambda-function.zip 第四步:测试Lambda函数 通过AWS控制台,生成测试事件,并运行函数。最后,检查日志以及结果是否合理。 以上就是实现Node函数架构的步骤,当然这只是一个简单的例子,实际情况中,可能需要更加复杂的逻辑和云平台配置。当我们成功部署Node函数,可以大大降低维护成本,同时加速应用开发和发布速度。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

凭栏听雨客

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值