简体   繁体   English

如何从node.js中的HTTP请求获取同步结果

[英]How to get a synchronuous result from an HTTP request in node.js

I am writing a node module as a wrapper around a Python module (to make that module available from node.js). 我正在编写一个节点模块作为Python模块的包装器(以使该模块可从node.js使用)。 This module works as a standalone script or as an HTTP server. 该模块可作为独立脚本或HTTP服务器使用。

When getting data from that script/server my function needs to return a value and can't do something in a callback function. 从该脚本/服务器获取数据时,我的函数需要返回一个值,并且无法在回调函数中执行任何操作。 At least that's how I understand it. 至少我是这样理解的。
(One possible client is a gitbook-plugin, and when that encounters a "block" it has to call the plugin->my-client-module and insert its return value into the generated HTML document.) (一个可能的客户端是gitbook插件,当遇到“块”时,它必须调用plugin-> my-client-module并将其返回值插入生成的HTML文档中。)

So either I'm seeing something wrong because I'm too new to Node.js (coming from Python) or I need a way to make the HTTP request synchronous. 所以要么我看到错误的原因是因为我对Node.js太陌生(来自Python),要么需要一种使HTTP请求同步的方法。

With the standalone script I can easily do it using ChildProcess.spawnSync, but not in an HTTP request. 使用独立脚本,我可以使用ChildProcess.spawnSync轻松完成此操作,但不能在HTTP请求中执行。

Well, I know people are always recommending to do things asynchronously in Node, so I'd also be happy about pointers how to achieve my goal that way. 好吧,我知道人们总是建议在Node中异步执行操作,所以我也对指针如何以这种方式实现目标感到高兴。 As said I expect clients of my module to pass me some data, pass that along to invoke the script or do a POST request on the server and return the processed data to the client. 如前所述,我希望模块的客户端向我传递一些数据,传递给它们以调用脚本或在服务器上进行POST请求,然后将处理后的数据返回给客户端。

You can achieve synchronous HTTP requests using web-workers. 您可以使用网络工作者来实现同步HTTP请求。
Here is more info on this topic: 这是有关此主题的更多信息:
https://developer.mozilla.org/zh-TW/docs/Web/API/XMLHttpRequest/Synchronous_and_Asynchronous_Requests#Example_Synchronous_HTTP_request_from_a_Worker https://developer.mozilla.org/zh-TW/docs/Web/API/XMLHttpRequest/Synchronous_and_Asynchronous_Requests#Example_Synchronous_HTTP_request_from_a_Worker


Edit: 编辑:

You can make synchronous requests from Node.Js. 您可以从Node.Js发出同步请求。 The following module should help: https://www.npmjs.com/package/sync-request 以下模块应有所帮助: https : //www.npmjs.com/package/sync-request

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

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