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
Related
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 :)
I can't figure out how to get my server to respond with Hello World.
I don't even know what IP address is. Is the ip listed on the tab of my terminal it?
I just created an EC2 environment with the default Node.js template.
Do I need to setup more things beforehand?
https://i.stack.imgur.com/4m85x.png
Try the solution bellow and let me know if you need any explanation:
const http = require("http");
const port = 3000; // make sure the port number is not used
const requestHandler = (req, res) => {
req.on('Error occurerd', (err) => {
console.error(err);
res.end();
});
res.end("Hello from AWS Cloud9!");
}
const server = http.createServer(requestHandler);
server.listen(port, () => {
console.log(`Server is listening on port ${port}!`);
// Run your script then copy past this url in your browser 127.0.0.1:3000
});
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);
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.
I've done this from scratch and it still gives me an error...
I've run
express test
then
cd test && npm install
I've edited the app.js adding a route such this:
app.get('/test',function(req,res) {
res.writeHead(200, {"Content-Type": "application/json"});
return res.send('{"a":3}');
});
Then I've run node
node app.js
And when I try to access http://server/test I get
Error: Can't set headers after they are sent.
I'm using
Node v4.2.1, Express 2.5.8, npm 3.4.0.
This just happens with Express, if I create a simple server on Node I can use writeHead.
When res.writeHead(200, {"Content-Type": "application/json"});,you send all the response headers to the client,so you can not send header again.
Because res.send is the function of express's response object,I look the source code of this send function:
chunk is what you send here : String('{"a":3}')
this.set('Content-Type', setCharset(type, 'utf-8')) here express helps us concat our content-type with utf-8 so server needs to send header again
That is why you get the error.
Ps.
Sorry for my bad english and I hope you understand what I try to explain.
What about using res.setHeader
var express = require('express');
var app = express();
app.get('/', function (req, res) {
res.setHeader("Content-Type","application/json");
res.send('{}');
});
var server = app.listen(3000, function () {
var host = "localhost";
var port = server.address().port;
console.log('Example app listening at http://%s:%s', host, port);
});