localhost:5000 is not loading my server!! Help needed - node.js

I am learning node and was creating a server using Traversy media video on node . Now before this I made a server using w3schools documentation and it worked . But us not working using Traversy Media's way.
The callback in the .listen is working but in browser it says 'Problem loading page'.
const http = require('http');
const server = http.createServer((req , res) => {
console.log(req.url);
});
const PORT =5000;
server.listen(PORT , () => console.log(`server running at ${PORT}`));
browser keeps loading but never stops loading.

Please Read the documentation of how to create a server that will help you immensly.
const server = http.createServer((req , res) => {
console.log(req.url);
});
In this case you are just printing the req.url without actually returning any response to the browser.
A proper hello world example will be:
http.createServer(function (req, res) {
res.write('Hello World!'); //write a response to the client
res.end(); //end the response
}).listen(8080);

Related

form nodejs http server, in browser we get 'domain' did not send any Data. ERR_EMPTY_RESPONSE

NOTE: this issue is happening in one linux machine and I have tested this in other linux machines, there it is working fine.
I created http server using nodejs http package as below:
DOES NOT WORK
const http = require('http');
const fs = require('fs');
const hostname = '0.0.0.0';
const port = 9001;
const printContent = function (content) {
console.log('***** Content of File STARTS *****\n');
console.log(content);
console.log('\n*** Content of file: ENDS *****');
}
const server = http.createServer((req, res) => {
setTimeout(function () {
// printContent('html');
res.statusCode = 200;
res.setHeader('Content-Type', 'text/html');
res.end('Hello');
}, 0);
console.log('*** function ends ***');
});
// server.timeout = 5000;
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
In this case response ends with ERR_EMPTY_RESPONSE
but when I remove setTimeout it works fine.
WORKS FINE:
const server = http.createServer((req, res) => {
printContent('Hello');
res.statusCode = 200;
res.setHeader('Content-Type', 'text/html');
res.end('Hello');
});
server.listen(9001);
This is very strange behaviour I am facing that If i make something asyn does not work.
Try using res.send not end so something like:
res.status(200).send("Hello");
Also I recommend using postman for debugging.
#Thomas Morris... thanks for the quick reply.
I am posting this answer so that if any one faces this issue should not spend as much time as I did.
Since it was not working in one machine and was working in another. So I thought of replacing the node binary and after I did this, the above code started working. The node binary itself was corrupt.
I have spent around 4 days to reach to this solution...really weird :)

Edit the response after a redirect (node.js & express)

I have a Nodejs express app which receives POST requests (XML) and simply redirects them to a different host replying to the original caller (also with an XML message).
var app = require('express')();
app.post('/', function(req, res) {
res.redirect(307, 'http://localhost:8888/');
});
app.listen(3000, function() {
console.log('Application listening on http://localhost:3000/');
});
What I am trying to achieve is to modify the response from the second host (localhost:8888). How do I intercept and edit the response from the second host before it reaches the original caller?
I cannot figure it out from the documentation so any help would be very appreciated, thank you.
You cannot do that as the response from server 2 is fetched by the client handling the redirect (e.g. your browser). You have to fetch the response yourself in the server side, modify it and send it back.
var app = require('express')();
var request = // your preferred http library
app.post('/', function(req, res) {
request.get('http://localhost:8888/', function (err, response) {
if (err) {
return res.error(err);
}
// Here you have the response, you can modify it.
res.send(response.body);
});
});
app.listen(3000, function() {
console.log('Application listening on http://localhost:3000/');
});

Node index.js command is keep ignored in window powershell

I'm trying to run index.js in localhost.
So, I make index.js like this.
const http = require('http');
http.createServer((req, res) => {
res.end('Hello');
}).listen(3000, ()=> {
console.log('running');
})
I typed node index.js but there is nothing in the console and it just turns off by itself.
There is nothing on console.
like this.
I typed that thing at PowerShell and git bash but none of them works.
I tried another port like 8080 or 8000 but it's not working.
And I also used forever, pm2, and nodemon but it doesn't work, too.
I think it's something like a firewall problem.
But I don't know what's wrong.
Try to break your code.
It might be because your code does not hold the instance of the server, it clear itself ... hence the listen promise isn't even reached.
const http = require('http');
const server = http.createServer((req, res) => {
res.end('Hello');
})
server.listen(3000, ()=> {
console.log('running');
})
## Try below code please
var http = require('http');
//create a server object:
http.createServer(function (req, res) {
res.write('Hello World!'); //write a response to the client
res.end(); //end the response
}).listen(8080); //the server object listens on port 8080

Node.js + React: How to POST

Follow on from this question: Axios can GET but not POST to the same URL
I've been trying to figure this out for too long now.
I want to POST from my React app to a .JSON file. Can anyone tell me what I'm doing wrong?
My AJAX POST function using axios always returns a 404. I'm listening for it on the node server but app.post never fires.
Thanks.
POST request from my React app:
postJson = (postJsonData) => {
axios.post('./postJson/', {
postJsonData
})
.then(function (response) {
console.log("success!");
console.log(response);
})
.catch(function (error) {
console.log(error);
});
}
app.js (node server):
/*========== Default Setup for node server copied from node website ==========*/
const http = require('http');
const hostname = '127.0.0.1';
const port = 3001;
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('Hello World\n');
});
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
/*========== Listen for POST (Trying to get the data from my REACT app
- will then assign it to "obj" below) ==========*/
var express = require("express");
var myParser = require("body-parser");
var app = express();
app.post("./postJson/", function(request, response) {
console.log("MURRRR");
console.log(request.body); //This prints the JSON document received (if it is a JSON document)
/*=== JSON Stuff ===*/
var jsonfile = require('jsonfile')
var file = './scene-setup.json'
var obj = {name: 'JP'}
jsonfile.writeFile(file, obj, function (err) {
console.error(err)
})
});
//Start the server and make it listen for connections on port 3000
app.listen(3000, function(){
console.log("server is listening to 3000");
});
Two things I noticed:
Your post endpoint doesn't need a leading "." I would make it just "/postJson"
Make sure you are posting to "http://localhost:3000/postJson"
Make sure you have the network tab open to see the actual URL you are requesting to.
Cheers
Turns out both react and my node server were running on localhost:3000 simultaneously which is apparently not okay.
Running my node server on localhost:3001 from a new command line window allowed me to do both at the same time.
Not sure how this would work when making a production build though.

Axios can GET but not POST to the same URL

I'm building a react app
In one component I'm writing this GET request which works:
In another component I'm writing this POST request:
Which then returns this 404 error:
And I have no idea how my GET works but my POST returns 404:not found when I'm requesting the same file both times?
UPDATE:
I'm running a node.js server now but it's a bit of a frankenstein's monster as this really isn't an area I have an understanding of. Does anyone know what I'm doing wrong?
// Server setup from node.js website
const http = require('http');
const hostname = '127.0.0.1';
const port = 3000;
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('Hello World\n');
});
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
// Trying to listen for data from React app to feed into JSON (broken)
var express = require("express");
var myParser = require("body-parser");
var app = express();
app.use(myParser.urlencoded({extended : true}));
app.post("/scene-setup.json", function(request, response) {
console.log(request.body); //This prints the JSON document received (if it is a JSON document)
});
app.listen(3001);
// Updating JSON file with "obj" (working)
var jsonfile = require('jsonfile')
var file = './scene-setup.json'
var obj = {name: 'JP'}
jsonfile.writeFile(file, obj, function (err) {
console.error(err)
})
Axios is used for making HTTP requests. So, you should have a backend server running that can handle these requests. I am not sure what exactly is the data that you want to save. If you need access to that data, should be saving it on the backend.
If you want to save some data just on the client side, HTML5 filesystem API might be something you want to look at. It can manage some data in the limited sandboxed part of user's filesystem.

Resources