Why is there a double console.log? [duplicate] - javascript

This question already has answers here:
node.js beginner - why does this receive 2 responses?
(1 answer)
Why does node.js, http-server, show that there are two request coming?
(1 answer)
Closed 7 years ago.
Description:
Hello, following a simple and straight forward tutorial. Everything works fine, but I was just curious as to why I'm getting a double request received when I refresh/access my page?
Part of my code:
function onRequest(request, response){
console.log('request received');
response.writeHead(200, {"Content-Type": "text/plain"});
response.write('Hello world baby');
response.end();
}
//creating server
http.createServer(onRequest).listen(8888);
console.log("server has started");
Screenshot:

Your browser is looking for the favicon.ico, then it sends a request for the actual content. Try to console.log both the request and response to get more information.

Related

Google App Scripts ReferenceError: URLSearchParams is not defined [duplicate]

This question already has answers here:
ReferenceError: Headers is not defined in Google scripts
(1 answer)
How to get an audio response from an API call within google app to play in speakers
(1 answer)
FileReader not defined in Apps Script
(1 answer)
How to use payload with method get?
(1 answer)
Which JavaScript features are available in Google Apps scripts?
(1 answer)
Closed 4 months ago.
This post was edited and submitted for review 4 months ago and failed to reopen the post:
Original close reason(s) were not resolved
I am trying to access an API in an apps scripts function. I have tested my code in VS code and it works just fine, but when I run it in apps scripts, I get an error saying "ReferenceError: URLSearchParams is not defined". Does anyone know of a fix? None of the similar questions offer a viable solution.
Code:
async function ApiTest() {
let status = "watching";
let num_watched_episodes = 10;
let token = "MyTokenIsHere";
let id = 50346;
const urlParams = new URLSearchParams({
status: status,
num_watched_episodes: num_watched_episodes,
});
fetch('https://api.myanimelist.net/v2/anime/' + id + '/my_list_status', {
method: "PATCH",
headers: {
'Authorization': 'Bearer ' + token,
},
body: urlParams,
})
}

Require is not define [duplicate]

This question already has answers here:
Javascript require() function giving ReferenceError: require is not defined
(6 answers)
Closed 2 years ago.
when I tried to send an email using nodemailer, after I insert these into my web project, and I get an error "require is not defined". Can I know how to solve it?
var nodemailer = require('nodemailer');
var transporter = nodemailer.createTransport({
service:'gmail',
auth:{
user:'xxx#gmail.com',
pass:'xxxxxxx'
}
});
var mailOptions = {
from:'xxx#gmail.com',
to: 'xxx#gmail.com',
subject:'Thanks for using!',
text:'Thanks!'
};
transporter.sendMail(mailOptions,function(error, info){
if(error){
console.log(error);
}else
console.log('Email sent: '+ info.response);
});
I am assuming you are trying to do this on the frontend. Nodemailer is a package that is made to be run on a backend node.js server. You do not have node listed for the questions tags so that is why I am assuming this. If this is not the case then check out:
http://requirejs.org/docs/download.html
Add this to your project: https://requirejs.org/docs/release/2.3.5/minified/require.js
and take a look at this http://requirejs.org/docs/api.html

nodeJs how to make http post request execute [duplicate]

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?

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

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