nodeJs how to make http post request execute [duplicate] - javascript

This question already has answers here:
How to wait until a predicate condition becomes true in JavaScript?
(23 answers)
How to prevent Node.js from exiting while waiting for a callback?
(8 answers)
Closed 2 years ago.
I have narrow down my problem to this,
I want to send post request to an API server but the post request sent only after the program exits.
my main.js:
var request = require("request");
send_post_to_server = function(name, responseCallback, outconfig) {
var outconfig = outconfig || {...};
request.post({
url: 'http://localhost:3000/api/backtest',
json: outconfig
}, function optionalCallback(error, response, body) {
responseCallback(error, response, body);
});
}
send_post_to_server ('first post request', my_response_callback);
send_post_to_server ('second post request', my_response_callback);
while(true); // with the loop, the server never gets the post requests.
If I remove the while loop and the program exits, it dose work and I do get the response to optionalCallback and responseCallback. But with the loop, the server dose not get the request.
why is that happened? and how can I make the program send the request? some kind of flush?
to run the program I use:
node main.js and npm istall request for the request module.

Because while(true); is blocking the thread and Node.js using single thread. Prefer asynchronous to do the operation. See also: https://nodejs.org/en/docs/guides/event-loop-timers-and-nexttick/
If you want to keep the Node.js process not terminating there is an answer for this
How to forcibly keep a Node.js process from terminating?

Related

JS - send WS message, wait for response, then send again depending on the response (all inside one function)

My goal is to, in one function, send a ws message:
ws.send(message),then wait for server response, which is handled by ws.onmessage = async (event) => - and depending on the server answer, send next message inside the same function
The problem is that I cannot receive response from the server before leaving the function. What tool would be the best to use in this case? (Im still at begginer level in JS)
Full code of the function is:
function ComboAction(data){
ws.send('message1')
//here i want to wait for server's response and continue this function depending on the response.
//wait for server response?
ws.send('message depending on server response to first message')
}
I was wondering out with promises? or the => method, but it's out of my reach for now.
Any tips will be greatly appreciated!

Accessing the data from a Node JS GET request without chaining callback functions

I'm using node.js simply so that I can run scheduled tasks and use GET requests. I'll paste some code that displays what I want to do, although it doesn't work for an obvious reason:
const http = require("http");
const request = require("request");
http.createServer(function (req, res) {
res.writeHead(200, {"Content-Type": "text/html"});
res.write("Hello, World!");
let a = getRequest();
console.log(a);
res.end();
}).listen(8080);
function getRequest() {
let b;
request("http://www.google.com", function(err, res, body) {
b = body;
})
return b;
}
So the b from the body does not work due to how the request is asynchronous and this leaves b as undefined when it is eventually printed. I know the way these callback functions are supposed to be used is to keep chaining of the callback function since that's the only place where the contents of body can be accessed. However, I don't want to keep chaining off functions because it completely destroys the structure of the program. I want to keep all my node server commands inside the http.createServer block. I don't want to place them in functions called from inside the callback function. In this example it doesn't really make sense for the process to be asynchronous since there's only 1 get request anyway and it can't be displayed in console.log until it's received anyway.
I just need a simple way to scrape data with get requests. What would be perfect is if I had some function that I could give a bunch of links, it gets the raw html from them, and then it waits for them to all be done so that I can process all the data at once.
How can something like this be implemented in Node.js?
You can do that using this module: sync-request.
With this module you will be able to make synchronous web requests from your NodeJS code.

javascript synchronous asynchronous query [duplicate]

This question already has answers here:
I know that callback function runs asynchronously, but why?
(3 answers)
Closed 5 years ago.
I am new to Javascript.
Below nodejs code runs synchronously, I do not undestand, why?
var http = require("http");
var fs = require("fs");
http.createServer(function (request, response) {
// Send the HTTP header
// HTTP Status: 200 : OK
// Content Type: text/plain
response.writeHead(200, {'Content-Type': 'text/plain'});
// Send the response body as "Hello World"
response.end('Hello World\n');
}).listen(8081);
// Console will print the message
console.log('Server running at http://127.0.0.1:8081/');
var data = fs.readFileSync('input.txt');
console.log(data.toString());
console.log("Program Ended");
I got output as:
Server running at http://127.0.0.1:8081/
Tutorials Point is giving self learning content
to teach the world in simple and easy way!!!!!
Program Ended
Below nodejs code runs asynchronously, I do not understand, why? I agree there is a callback in the readFile function, so why it behaves asynchronously?
var http = require("http");
var fs = require("fs");
http.createServer(function (request, response) {
// Send the HTTP header
// HTTP Status: 200 : OK
// Content Type: text/plain
response.writeHead(200, {'Content-Type': 'text/plain'});
// Send the response body as "Hello World"
response.end('Hello World\n');
}).listen(8081);
// Console will print the message
console.log('Server running at http://127.0.0.1:8081/');
fs.readFile('input.txt', function(err, data){
console.log(data.toString());
});
console.log("Program Ended");
Here is the output:
Server running at http://127.0.0.1:8081/
Program Ended
Tutorials Point is giving self learning content
to teach the world in simple and easy way!!!!!
Could you please someone explain me clearly why above is behaving like that. Are callbacks always asynchronous? I also would like to know how execution happens internally for callback functions.
Assume a control came to the line readFile function (which is having callback in it), so why does control immediately executes another statement? If control transers to another statement, who will execute callback function? After callback returns some value, does control again comes back to same statement ie., 'readFile' line?
Sorry for stupid query.
The synchronous version (fs.readFileSync) will block the execution until the file is read and return the result containing the file contents:
var data = fs.readFileSync('input.txt');
This means that the next line of code will not be executed until the file is completely read and the result returned to the data variable.
The asynchronous version on the other (fs.readFile) hand will immediately return the execution to the next line of code (which is console.log("Program Ended");):
fs.readFile('input.txt', function(err, data) {
// This callback will be executed at a later stage, when
// the file content is retrieved from disk into the "data" variable
console.log(data.toString());
});
Then later, when the file contents is completely read, the passed callback will be invoked and so you see the contents of the file printed at a later stage. The second approach is recommended because you are not blocking the execution of your code during the file I/O operation. This allows you to perform more operations at the same time, while the synchronous version will freeze any other execution until it fully completes (or fails).

So about requesting in node.js

Ok look at this code..
var http = require('http');
var handleRequest = function (request, response){
response.writeHead(200,{"context-type":"text/plain"});
response.end('Welcome to the node club! :)');
}
//the createServer method... creates a server WOW!
http.createServer(handleRequest).listen(8888);
console.log('The servers are running and the bacon is stopping');
It seems simple enough, the handleRequest function will create a writeHead function when the node will allow me to respond ...right? And if that is the case, I will be able to write out "Welcome to the node club" in the end method. The thing I don't understand about node is the request variable or object or whatever. In the function am I requesting the node? Or is the node requesting me to run a function? I'm not using the request variable in the function so would it still run if I left it out?
The argument to http.createServer is a function to be called on each request. The function is documented as
function (request, response) { }
request is an instance of http.IncomingMessage and response is an instance of http.ServerResponse.
What you do in this function is up to you; it can be anything.
However, virtually all web applications end up writing an answer to the client, and that's done via the response object. Also, since an application that serves just one page is quite limited, most applications also want to get information from the HTTP request, including the path requested (something like '/questions/37265770/so-about-requesting-in-node-js', in request.path), HTTP POST parameters and the like.
Your function gets called with two arguments, the first of which is the request object, the second the response object. There is no magic involved - you seem to call magic "node", but that's just the name of the project.

nodejs - why does my async function run twice? [duplicate]

This question already has answers here:
nodejs - http.createServer seems to call twice
(3 answers)
Closed 6 years ago.
I am new to node.js and learning from tutorials online.
I was trying out the following piece of code :
var http = require("http");
// create a server
http.createServer(function(req, res) {
console.log("Received Request");
res.writeHead(200, {'Content-Type':'application/json'});
res.end("{'status':'200', 'message':'Hello World'}");
console.log("Response Sent");
}).listen(process.env.PORT, process.env.IP);
I did receive the correct response but in console the output was :
Received Request
Response Sent
Received Request
Response Sent
I wanted to know why was my code running twice ?? Am I making some mistake ?
Please help !!
the best way to debug is to check the url
var http = require("http");
// create a server
http.createServer(function(req, res) {
console.log(req.url);//add this line, I hope it will help
console.log("Received Request");
res.writeHead(200, {'Content-Type':'application/json'});
res.end("{'status':'200', 'message':'Hello World'}");
console.log("Response Sent");
}).listen(process.env.PORT, process.env.IP);
Also as Bassam Rubaye pointed out it might most likely due to favicon in your case
When you access a url using the browser , the browser will send a request for the favicon, then send another request for the content, that's why you are seeing two requests !
Use PostMan and request the same url , you should see only one request.
No mistake--this is normal! Your browser makes multiple requests. There's a similar answer at nodejs - http.createServer seems to call twice.
Hope you're having fun learning node.js!

Categories

Resources