Read from request method in Node.js - javascript

I'm writing a Node.js script that converts HTML files to ENML (Evernote Markup Language).
Now this script correctly converts an existing HTML file to the desired ENML output. Now, I have the following question:
Client will be sending an HTML file in JSON format. How do I listen for all incoming requests, take the JSON object, convert to ENML, and write back the response to the original request?
My code for this is as follows:
var fs = require('fs');
var path = require('path');
var html = require('enmlOfHtml');
var contents = '';
var contents1 = '';
fs.readFile(__dirname + '/index.html', 'utf8', function(err, html1){
html.ENMLOfHTML(html1, function(err, ENML){ //using Enml-js npm
contents1=ENML;
});
});
var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'application/json'});
res.write(contents1);
}).listen(4567, "127.0.0.1");
Thanks!

I guess that the client will make POST requests to your server. Here is how you could get the send information:
var processRequest = function(req, callback) {
var body = '';
req.on('data', function (data) {
body += data;
});
req.on('end', function () {
callback(qs.parse(body));
});
}
var http = require('http');
http.createServer(function (req, res) {
processRequest(req, function(clientData) {
html.ENMLOfHTML(clientData, function(err, ENML){ //using Enml-js npm
contents1 = ENML;
res.writeHead(200, {'Content-Type': 'application/json'});
res.write(JSON.stringify(contents1));
});
});
}).listen(4567, "127.0.0.1");

You can use the Node's request module.
request('http://www.example.com', function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log(body);
}
});

Related

How to print data from a csv file on a browser in nodejs

I want to read a csv file and whenever someone connects to my server it prints the content of the file in their browser.
I have this module called 'lecture_csv' that lets me read the file and directly print it in the terminal:
var csv = require('csv-parser')
var fs = require('fs')
function lecture_csv(fileName) {
fs.createReadStream(fileName)
.pipe(csv())
.on('data', (row) => {
//console.log(row)
return row;
})
.on('end', () => {
console.log('fichier lu');
});
}
exports.lecture_csv = lecture_csv
What I want is to print 'row' on the client browser.
However in my main:
let lecture = require('./lecture_csv');
var http = require('http');
//let app = require('./app');
var fileName = 'test_file.csv'
var string = ''
//lecture.lecture_csv(fileName);
http.createServer(function(req, res){
res.writeHead(200, {'Content-Type': 'text/plain'});
res.write(lecture.lecture_csv(fileName));
res.end();
}).listen(9000);
I have an error saying I can't use res.write as the parameter in undefined instead of a string.
Is there a way to get 'row' and print it on the client browser?
I am still very new to nodejs therefore any tips is welcomed.
You have to read file and send its contents ,like below
let lecture = require('./lecture_csv');
let fs=require("fs");
var http = require('http');
var fileName = './test_file.csv'
var string = ''
//lecture.lecture_csv(fileName);
http.createServer(function(req, res){
fs.readFile(fileName, 'utf8', function(err, contents) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.write(contents);
res.end();
});
}).listen(9000);

Node.js API returns JSON in terminal but not in browser

Having a strange problem. Been searching for answers but nothing turns up. I'm doing a node api tutorial and it returns JSON from my mongoDB database in my terminal when I perform any GET request but in my browser or postman I get nothing back, only in the terminal do I get any response. When I try a POST in postman it says it can't connect to the backend.
here is my code :
var http = require('http');
var url = require('url');
var database = require('./database');
// Generic find methods (GET)
function findAllResources(resourceName, req, res) {
database.find('OrderBase', resourceName, {}, function (err, resources) {
res.writeHead(200, {'Content-Type': 'application/json'});
res.end(JSON.stringify(resources));
});
};
var findResourceById = function (resourceName, id, req, res) {
database.find('OrderBase', resourceName, {'_id': id}, function (err, resource) {
res.writeHead(200, {'Content-Type': 'application/json'});
res.end(JSON.stringify(resource));
});
};
// Product methods
var findAllProducts = function (req, res) {
findAllResources('Products', req, res);
};
var findProductById = function (id, req, res) {
findResourceById('Products', id, req, res);
};
// Generic insert/update methods (POST, PUT)
var insertResource = function (resourceName, resource, req, res) {
database.insert('OrderBase', resourceName, resource, function (err, resource) {
res.writeHead(200, {'Content-Type': 'application/json'});
res.end(JSON.stringify(resource));
});
};
// Product methods
var insertProduct = function (product, req, res) {
insertResource('OrderBase', 'Product', product, function (err, result) {
res.writeHead(200, {'Content-Type': 'application/json'});
res.end(JSON.stringify(result));
});
};
var server = http.createServer(function (req, res) {
// Break down the incoming URL into its components
var parsedURL = url.parse(req.url, true);
// determine a response based on the URL
switch (parsedURL.pathname) {
case '/api/products':
if (req.method === 'GET') {
// Find and return the product with the given id
if (parsedURL.query.id) {
findProductById(id, req, res)
}
// There is no id specified, return all products
else {
findAllProducts(req, res);
}
}
else if (req.method === 'POST') {
//Extract the data stored in the POST body
var body = '';
req.on('data', function (dataChunk) {
body += dataChunk;
});
req.on('end', function () {
// Done pulling data from the POST body.
// Turn it into JSON and proceed to store it in the database.
var postJSON = JSON.parse(body);
insertProduct(postJSON, req, res);
});
}
break;
default:
res.end('You shall not pass!');
}
});
server.listen(8080);
console.log('Up and running, ready for action!');
You have several callbacks with err as first argument but you are not treating any potential error. It means if something is going wrong, you are not catching it and returning an error. I don't know if this has anything to do with it, but as a practice (not even "best", but general practice) instead of doing this
function (err, resource) {
res.writeHead(200, {'Content-Type': 'application/json'});
res.end(JSON.stringify(resource));
}
do this
function (err, resource) {
if(err){
// do something to warn the client and stop here
}
res.writeHead(200, {'Content-Type': 'application/json'});
res.end(JSON.stringify(resource));
}
Try that, see if you are actually running into errors before trying to output an answer.
https://nodejs.org/api/http.html#http_response_end_data_encoding_callback
The response end method not send data to response socket. Maybe you change it
res.writeHead(200, {'Content-Type': 'application/json'});
res.end(JSON.stringify(resource));
res.writeHead(200, {'Content-Type': 'application/json'});
res.write(JSON.stringify(resource));
res.end();
if you want socket to close to do something, you can into callback to end.
res.end(#logHandle());
var MongoClient = require('mongodb').MongoClient;
var assert = require('assert');
var connect = function (databaseName, callback) {
var url = 'mongodb://localhost:27017/' + databaseName;
MongoClient.connect(url, function (error, database) {
assert.equal(null, error);
console.log("Successfully connected to MongoDB instance!");
callback(database);
})
};
exports.find = function (databaseName, collectioName, query, callback) {
connect(databaseName, function (database) {
var collection = database.collection(collectioName);
collection.find(query).toArray(
function (err, documents) {
assert.equal(err, null);
console.log('MongoDB returned the following documents:');
console.dir(JSON.parse(JSON.stringify(documents)));
//console.dir(documents);
callback(null, documents);
}
)
database.close();
})
};
I think we are going through the same tutorial, this is my solution of 'database.js', works for me.

Get request body for post operation

I use the http module and I need to get the req.body
currently I try with the following without success .
http.createServer(function (req, res) {
console.log(req.body);
this return undfiend ,any idea why?
I send via postman some short text...
Here's a very simple without any framework (Not express way).
var http = require('http');
var querystring = require('querystring');
function processPost(request, response, callback) {
var queryData = "";
if(typeof callback !== 'function') return null;
if(request.method == 'POST') {
request.on('data', function(data) {
queryData += data;
if(queryData.length > 1e6) {
queryData = "";
response.writeHead(413, {'Content-Type': 'text/plain'}).end();
request.connection.destroy();
}
});
request.on('end', function() {
request.post = querystring.parse(queryData);
callback();
});
} else {
response.writeHead(405, {'Content-Type': 'text/plain'});
response.end();
}
}
Usage example:
http.createServer(function(request, response) {
if(request.method == 'POST') {
processPost(request, response, function() {
console.log(request.post);
// Use request.post here
response.writeHead(200, "OK", {'Content-Type': 'text/plain'});
response.end();
});
} else {
response.writeHead(200, "OK", {'Content-Type': 'text/plain'});
response.end();
}
}).listen(8000);
express framework
In Postman of the 3 options available for content type select "X-www-form-urlencoded".
app.use(bodyParser.urlencoded())
With:
app.use(bodyParser.urlencoded({
extended: true
}));
See https://github.com/expressjs/body-parser
The 'body-parser' middleware only handles JSON and urlencoded data, not multipart
req.body is a Express feature, as far as I know... You can retrieve the request body like this with the HTTP module:
var http = require("http"),
server = http.createServer(function(req, res){
var dataChunks = [],
dataRaw,
data;
req.on("data", function(chunk){
dataChunks.push(chunk);
});
req.on("end", function(){
dataRaw = Buffer.concat(dataChunks);
data = dataRaw.toString();
// Here you can use `data`
res.end(data);
});
});
server.listen(80)

Node JS OR Express JS HTTP GET Request

I am using express.js and I need to make a call to HTTP GET request ,to fetch JSON data .Please suggest me some good node js/express js modules/lib to perform get/post request .
Node.js provides an extremely simple API for this functionality in the form of http.request.
var http = require('http');
//The url we want is: 'www.random.com/integers/?num=1&min=1&max=10&col=1&base=10&format=plain&rnd=new'
var options = {
host: 'www.random.com',
path: '/integers/?num=1&min=1&max=10&col=1&base=10&format=plain&rnd=new'
};
callback = function(response) {
var str = '';
//another chunk of data has been recieved, so append it to `str`
response.on('data', function (chunk) {
str += chunk;
});
//the whole response has been recieved, so we just print it out here
response.on('end', function () {
console.log(str);
});
}
http.request(options, callback).end();
Here I attach some more examples with POST and custom headers. If you don't need special things, I'd stick to the native code.
Besides, Request, Superagent or Requestify are pretty good libraries to use.
var express = require('express');
var app = express();
var fs = require('fs');
app.get('/', function (req, res) {
fs.readFile('./test.json', 'utf8', function (err, data) {
if (err) {
res.send({error: err});
}
res.send(data);
})
});
var server = app.listen(3001, function () {
console.log('Example app listening port 3001');
});

Node.js beginner- request without query strings

I'm new to node.js. A project I'm working on requires that a large array (625 items) be stored in a MySQL database as a string and I'm using Node MySQL to accomplish that.
Right now I have it so that the row is updated when a request is made to "/(column name)?(value)". Unfortunately, it didn't take long to learn that passing 625 items as a string to node isn't the most efficient way of doing things.
Do you have any suggestions for alternate methods of passing a large array as a string besides querystrings?
var http = require('http'),
mysql = require("mysql"),
url = require("url"),
express = require("express");
var connection = mysql.createConnection({
user: "root",
database: "ballot"
});
var app = express();
app.use(express.bodyParser());
app.options('/', function (request, response)
{
response.header("Access-Control-Allow-Origin", "*");
response.end();
});
app.get('/', function (request, response)
{
connection.query("SELECT * FROM pathfind;", function (error, rows, fields) {
for(i=0;i<rows.length;i++)
{
response.send('<div id="layers">'+rows[i].layers+'</div> \
<div id="speed">'+rows[i].speed+'</div> \
<div id="direction">'+rows[i].direction+'</div>');
}
response.end();
});
});
app.post('/', function (request, response)
{
console.log(request.param('data', null));
var urlData = url.parse(request.url, true);
if(urlData.pathname = '/layers')
{
col = "layers";
}
else if(urlData.pathname = '/speed')
{
col = "speed";
}
else if(urlData.pathname = '/direction')
{
col = "direction";
}
req.addListener("data", function(data) {
connection.query("UPDATE pathfind SET "+col+"="+data+" WHERE num=0", function (error, rows, fields) {
if (error)
{
app.close();
}
});
});
});
app.listen(8080);**
EDIT: So now I know I need to use posts. I've rewritten the above code using express.js. Most examples that I look at online use posts with HTML forms, which is fine, but my project needs to post data via an AJAX request. Can someone show me how that data is parsed in node.js?
You can extract post data like this.
if (req.method == 'POST') {
var body = '';
req.on('data', function (chunk) {
body += chunk;
});
req.on('end', function () {
var postData = body.toString();
console.log(postData);
});
}

Categories

Resources