简体   繁体   English

如何制作一个非常简单的 node.js 服务器,它本身会发出 HTTP 请求?

[英]How can I make an incredibly simple node.js server which itself makes an HTTP request?

I have found very simple code that creates a server and displays a string, using the "http" module.我发现使用“http”模块创建服务器并显示字符串的非常简单的代码。 eg.例如。 from https://garywoodfine.com/simple-lightweight-nodejs-webserver/ :来自https://garywoodfine.com/simple-lightweight-nodejs-webserver/

var http = require('http');
var server = http.createServer(function (req, res) {
    var body = 'Amazing lightweight webserver using node.js\n';
    var content_length = body.length;
    res.writeHead(200, {
        'Content-Length': content_length,
        'Content-Type': 'text/plain' });
 
    res.end(body);
});
server.listen(3939);
console.log('Server is running on port 3939');

I have found very simple code that gets data over HTTP, using the "got" module.我发现使用“got”模块通过 HTTP 获取数据的非常简单的代码。 eg.例如。 fromhttps://nodesource.com/blog/express-going-into-maintenance-mode :来自https://nodesource.com/blog/express-going-into-maintenance-mode

const got = require('got');

(async () => {
    try {
        const response = await got('https://www.nodesource.com/');
        console.log(response.body);
        //=> '<!doctype html> ...'
    } catch (error) {
        console.log(error.response.body);
        //=> 'Internal server error ...'
    }
})();

However I am failing to integrate the two to create a server that, when visited, makes the HTTP call and returns the result.但是,我未能将两者集成以创建一个服务器,该服务器在访问时进行 HTTP 调用并返回结果。 I essentially just want to replace the var body = 'Amazing lightweight webserver using node.js\\n';我基本上只是想替换var body = 'Amazing lightweight webserver using node.js\\n'; line from the Gary Woodfine example with the output of the Nodesource example.来自 Gary Woodfine 示例的行与 Nodesource 示例的输出。

I'm not particularly looking for comments or questions as to why I would want to make something that does this, I'm trying to understand fundamentally why I can't just do what feels like a very simple and natural thing to do: return content based on a server side request to another web service.我并不是特别在寻找关于为什么我想做这样的事情的评论或问题,我试图从根本上理解为什么我不能做一件感觉非常简单和自然的事情:返回基于对另一个 Web 服务的服务器端请求的内容。 I get the impression that the issue is to do with the asynchronous paradigm and obviously I understand the performance improvements it offers, I'm failing to understand how you structure something that works for this simple usecase.我的印象是这个问题与异步范式有关,显然我理解它提供的性能改进,但我无法理解您如何构建适用于这个简单用例的东西。

With thanks to Brad for his comment , I now have code that integrates the two samples:感谢Brad评论,我现在有了集成两个示例的代码:

var http = require('http');
const got = require('got');

var server = http.createServer(function (req, res) {
    var body = (async () => {
        try {
            const response = await got('https://www.nodesource.com/');
            var body = response.body;
            var content_length = body.length;
            res.writeHead(200, {
                'Content-Length': content_length,
                'Content-Type': 'text/plain' });
            res.end(body);
            //=> '<!doctype html> ...'
        } catch (error) {
            console.log(error.response.body);
            //=> 'Internal server error ...'
        }
    })();
 });
server.listen(3939);
console.log('Server is running on port 3939');

This code can be stripped down further obviously, to the sort of level of simplicity I had in mind.这段代码显然可以进一步精简,达到我心目中的那种简单程度。

Where I was going wrong was by trying to handle all the http response code after the async block, when I needed to do it inside it.我出错的地方是尝试在 async 块之后处理所有http响应代码,当我需要在它里面做的时候。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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