Not able to set response status code, without ExpressJs - node.js

Not able to set response status code(after trying for 2 hours) in node.js 8.9
Tried : res.statusCode = 404; and res.writeHead(404,{});
Both didn't work.
Note: NOT using expressJs
Sample Code
var http = require('http');
//create a server object:
http.createServer(function (req, res) {
try{
res.write('Hie !'); //write a response to the client
res.statusCode = 404;
//res.writeHead(404,{});
res.end(); //end the response
}catch(e){
console.error(e);
}
}).listen(8080); //the server object listens on port 8080
Note: NOT using expressJs

Pretty simple, the statusCode has to be set before you write anything to the response stream, because otherwise it is an implicit 200 code.
Also, you should know that your try...catch block is useless in a callback scenario like that, unless you're doing some form of synchronous code that might fail.
If you update your code to the below, it'll work:
var http = require('http');
//create a server object:
http.createServer(function (req, res) {
res.statusCode = 404;
res.write('Hi!'); //write a response to the client
res.end(); //end the response
}).listen(8080); //the server object listens on port 8080
You could also use ES6 syntax, which some like better for various reasons:
const http = require('http');
http.createServer((req, res) => {
res.statusCode = 404;
res.write('Hi!');
res.end();
}).listen(8080);

As per Express V5
res.sendStatus(statusCode)
Express 5 no longer supports the signature res.send(status), where status is a number. Instead, use the res.sendStatus(statusCode) function, which sets the HTTP response header status code and sends the text version of the code: “Not Found”, “Internal Server Error”, and so on.
As per the Express (Version 4+) docs:
res.status(400);

Related

Is there a way to read in an http server (node.js)?

I have created a Server with Node.Js here is the Code
const http = require('http');
const server = http.createServer(function (req, res) {
res.statusCode = 200;
res.setHeader('Content-Type','text/html');
res.write(<input type="number" id="a">);
res.write("<style> #a {text-align:center} </style>");
/*Reading function */
res.end();
});
server.listen(8000);
Is there a way to get the innerHTML of the input(From the Client)?
Maybe u can help me :)
(For further explaination: The client should open the website, write something in the number field, then i want the innerHTML of the number field send to the server)

How can I make an incredibly simple node.js server which itself makes an HTTP request?

I have found very simple code that creates a server and displays a string, using the "http" module.
eg. from https://garywoodfine.com/simple-lightweight-nodejs-webserver/:
var http = require('http');
var server = http.createServer(function (req, res) {
var body = 'Amazing lightweight webserver using node.js\n';
var content_length = body.length;
res.writeHead(200, {
'Content-Length': content_length,
'Content-Type': 'text/plain' });
res.end(body);
});
server.listen(3939);
console.log('Server is running on port 3939');
I have found very simple code that gets data over HTTP, using the "got" module.
eg. from https://nodesource.com/blog/express-going-into-maintenance-mode:
const got = require('got');
(async () => {
try {
const response = await got('https://www.nodesource.com/');
console.log(response.body);
//=> '<!doctype html> ...'
} catch (error) {
console.log(error.response.body);
//=> 'Internal server error ...'
}
})();
However I am failing to integrate the two to create a server that, when visited, makes the HTTP call and returns the result. I essentially just want to replace the var body = 'Amazing lightweight webserver using node.js\n'; line from the Gary Woodfine example with the output of the Nodesource example.
I'm not particularly looking for comments or questions as to why I would want to make something that does this, I'm trying to understand fundamentally why I can't just do what feels like a very simple and natural thing to do: return content based on a server side request to another web service. I get the impression that the issue is to do with the asynchronous paradigm and obviously I understand the performance improvements it offers, I'm failing to understand how you structure something that works for this simple usecase.
With thanks to Brad for his comment, I now have code that integrates the two samples:
var http = require('http');
const got = require('got');
var server = http.createServer(function (req, res) {
var body = (async () => {
try {
const response = await got('https://www.nodesource.com/');
var body = response.body;
var content_length = body.length;
res.writeHead(200, {
'Content-Length': content_length,
'Content-Type': 'text/plain' });
res.end(body);
//=> '<!doctype html> ...'
} catch (error) {
console.log(error.response.body);
//=> 'Internal server error ...'
}
})();
});
server.listen(3939);
console.log('Server is running on port 3939');
This code can be stripped down further obviously, to the sort of level of simplicity I had in mind.
Where I was going wrong was by trying to handle all the http response code after the async block, when I needed to do it inside it.

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/');
});

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.

Unable to set headers in node.js in POST method

I have a case where i have to read the data from the request body and create a file and write the data into it. If the operation is successful I set the response header to 201 and add the location of file in Location header. The file creation is done using Java methods and node.js code is below.
var server = http.createServer(function(req, res)
{
var body = "";
req.on("data", function(chunk)
{
body += chunk.toString();
});
req.on("end", function() {
var rtn = obj.AddonPostMethod(filepath,body);
if(rtn.length < 13)
{
res.writeHead(201, {"Location" : rtn});
res.end();
}
else
{
res.writeHead(400, {"Content-Type" : application/json"});
res.write(''+rtn);
res.end();
}
});
}});
The problem is that the response headers are not getting updated and are always set to the default headers 200 Ok. In addition to this the server is always busy even after the response is received.
I don't think you're actually listening on a port with the code you reference.
var http = require('http');
http.createServer(function(req,res){
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello World\n');
}).listen(8000);
console.log('Server running at http://127.0.0.1:8000/');
You never declare the http object as actually listening on a port/ip with the .listen() function.
Also, you don't need to wait for the req object to emit anything to respond. The function is called when the request is complete. You can listen for specific requests and route them appopriately by storing the http.Server object to a variable.
var server = http.createServer();
server.listen(8000);
server.on('request', function(req,res){ /* do something with the request */ });
More documentation on the http object can be found on the node.js documents for http

Resources