I am making basic web server using nodejs and express module. It has to be able to respond to POST and GET requests. POST is just working fine, but GETdoesn't return anything. In console there's a textStatus of an error parserror and SyntaxError: Unexpected end of input at Object.parse (native) at jQuery.parseJSON error. I'm new to NodeJS and Express, please tell me where I went wrong.
var express = require('express'),
server = express(),
fs = require('fs');
server.use(express.static('../client'));
server.post('/students.json', function (req, res) {
var bodyStr = '';
req.on('data', function (chunk) {
bodyStr += chunk.toString();
});
req.on('end', function () {
fs.readFile('students.json', function (err, data) {
var encodedObj = data.toString('utf8'), //encoding what's inside of .json into human symbols
parsedObj = JSON.parse(encodedObj);
parsedObj.push(JSON.parse(bodyStr)); //adding newly created parsed obj into array
fs.writeFile('students.json', JSON.stringify(parsedObj), function (err) { //rewriting file with new array
if (err) {
console.log(err);
}
});
});
});
});
server.get('/students.json', function (req, res) {//what's wrong???
res.send();
});
var server = server.listen(8888);
What are you trying to res.send()? It looks empty to me. Try:
res.send('Hello World!'); // A string
...or...
res.send([{'name': 'Joe Student'},{'name': 'Sally Goestoskuhl'}]); // Array
...or...
res.send({}); // Empty json response
...or...
res.send(404); // Any integer is considered an HTTP error code
...or...
res.setHeader('Content-Type', 'application/json');
res.send(JSON.stringify({ variable: 'value' }));
...or...
// Assuming your json is in the public folder...
res.sendFile(path.join(__dirname, '../public', 'students.json'));
res.send(); on it's own just sends an empty response.
If you then try to json_decode it, you'll get an error.
If I interpret your question correctly, you want both POST and GET to return the same result?
You could do this pretty simply like this:
function sendJSON(req, res)
{
//JSON code from your existing server.post
}
app.get('/students.json', sendJSON);
app.post('/students.json', sendJSON);
Related
I'm creating an API with JS. While using the get method I'm not receiving the JSON data from the ./personal_data.js file. It's only displaying closed braces as response.
I'm attaching the code and output below. Any suggestions might be helpful.
const express = require('express');
const personal_data = require('./personal_data');
const app = express();
app.listen(3000, () => {
console.log('Listening on port 3000');
});
app.get('/', (req, res) => {
res.json({ Message: 'API is Working' }); // show messsage on serv
});
app.get('/personal_data', (req, res) => {
res.json(personal_data); // send employee json file
});
app.post('/personal_data',(req,res)=>{
res.send('post request')
})
json file with data
OUTPUT
Post man
Make sure you're exporting your data correctly. Use module.exports = ... instead of module.export = ... in your personal_data.js. Don't forget to restart your server once it's updated.
Check this sandbox where I show you the difference: CodeSandbox
I'm trying to send a post parameter (key: test, value: somevlaue) using PostMan using restify framework. For this I've used 2 methods and both are not working:
1st one shows this error:
{
"code": "InternalError",
"message": "Cannot read property 'test' of undefined"
}
2nd one (commented) shows only Error: someerror
Am I doing something wrong?
Here's my code:
var restify=require('restify');
var fs=require('fs');
var qs = require('querystring');
var bodyParser = require('body-parser');
var urlencodedParser = bodyParser.urlencoded({ extended: false })
var controllers = {};
var server=restify.createServer();
server.post("/get", function(req, res, next){
res.send({value: req.body.test,
error: "someerror"});
//**********METHOD TWO*********************
/*
if (req.method == 'POST') {
var body = '';
req.on('data', function (data) {
body += data;
});
req.on('end', function () {
var post = qs.parse(body);
res.send({
Data: post.test,
Error: "Someerror"
});
});
}
*/
});
server.listen(8081, function (err) {
if (err)
console.error(err);
else
console.log('App is ready at : ' + 8081);
});
With restify ^7.7.0, you don't have to require('body-parser') any more. Just use restify.plugins.bodyParser():
var server = restify.createServer()
server.listen(port, () => console.log(`${server.name} listening ${server.url}`))
server.use(restify.plugins.bodyParser()) // can parse Content-type: 'application/x-www-form-urlencoded'
server.post('/your_url', your_handler_func)
It looks like you might have your bodyparser set up incorrectly.
According to the docs under the body parser section you set up the parser in this manner:
server.use(restify.bodyParser({
maxBodySize: 0,
mapParams: true,
mapFiles: false,
.....
}));
The default is to map the data to req.params but you can change this and map it to req.body by setting the mapParams option to false
BodyParser
Blocks your chain on reading and parsing the HTTP request body.
Switches on Content-Type and does the appropriate logic.
application/json, application/x-www-form-urlencoded and
multipart/form-data are currently supported.
I am trying to run .get on a JSON file I've set up located at /scripts/src/data/*.json when I make the request I set the headers but I'm not sure how I actually return the resulting data or where I can view this request. Can someone offer any help?
JS
server.get('/scripts/src/data/*.json', function(req, res) {
res.setHeader("Content-Type", "application/json");
// return ??
});
You could use static middleware to serve your json files ,
server.use(express.static(__dirname + "/scripts/src/data"))
//other routes
In client side , you just should request GET localhost:port/file.json
Try this:
server.get('/scripts/src/data/*.json', function(req, res) {
res.setHeader("Content-Type", "application/json");
res.status(200);
res.json({
hello: "world"
});
// return ??
});
I'm having serious issues with an app I am building with Node.js, Express, MongoDB and Mongoose. Last night everything seemed to work when I used nodemon server.js to `run the server. On the command line everything seems to be working but on the browser (in particular Chrome) I get the following error: No data received ERR_EMPTY_RESPONSE. I've tried other Node projects on my machine and they too are struggling to work. I did a npm update last night in order to update my modules because of another error I was getting from MongoDB/Mongoose { [Error: Cannot find module '../build/Release/bson'] code: 'MODULE_NOT_FOUND'}. I used the solution in this answer to try and fix it and it didn't work and I still get that error. Now I don't get any files at all being served to my browser. My code is below. Please help:
//grab express and Mongoose
var express = require('express');
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
//create an express app
var app = express();
app.use(express.static('/public/css', {"root": __dirname}));
//create a database
mongoose.connect('mongodb://localhost/__dirname');
//connect to the data store on the set up the database
var db = mongoose.connection;
//Create a model which connects to the schema and entries collection in the __dirname database
var Entry = mongoose.model("Entry", new Schema({date: 'date', link: 'string'}), "entries");
mongoose.connection.on("open", function() {
console.log("mongodb is connected!");
});
//start the server on the port 8080
app.listen(8080);
//The routes
//The route for getting data for the database
app.get("/database", function(req, res) {
Entry.find({}, function(err, data) {console.log(err, data, data.length); });
});
//The route for posting data on the database
app.post("/database", function(req, res) {
//test new post
var newMonth = new Entry({date: '1997-10-30', link: 'https://wwww.youtube.com/'});
newMonth.save(function(err) {
if (err !== null) {
//object was not save
console.log(err);
} else {
console.log("it was saved!")
};
});
});
//create an express route for the home page at http://localhost:8080/
app.get('/', function(req, res) {
res.send('ok');
res.sendFile('/views/index.html', {"root": __dirname + ''});
});
//Send a message to the console
console.log('The server has started');
//The route for getting data for the database
app.get("/database", function(req, res) {
Entry.find({}, function(err, data) {console.log(err, data, data.length); });
});
//The route for posting data on the database
app.post("/database", function(req, res) {
//test new post
var newMonth = new Entry({date: '1997-10-30', link: 'https://wwww.youtube.com/'});
newMonth.save(function(err) {
if (err !== null) {
//object was not save
console.log(err);
} else {
console.log("it was saved!")
};
});
});
These routes don't send anything back to the client via res. The bson error isn't a big deal - it's just telling you it can't use the C++ bson parser and instead is using the native JS one.
A fix could be:
//The route for getting data for the database
app.get("/database", function(req, res) {
Entry.find({}, function(err, data) {
if (err) {
res.status(404).json({"error":"not found","err":err});
return;
}
res.json(data);
});
});
//The route for posting data on the database
app.post("/database", function(req, res) {
//test new post
var newMonth = new Entry({date: '1997-10-30', link: 'https://wwww.youtube.com/'});
newMonth.save(function(err) {
if (err !== null) {
res.status(500).json({ error: "save failed", err: err});
return;
} else {
res.status(201).json(newMonth);
};
});
});
updated june 2020
ERR_EMPTY_RESPONSE express js
package.json
"cors": "^2.8.4",
"csurf": "^1.9.0",
"express": "^4.15.4",
this error show when you try to access with the wrong HTTP request. check first your request was correct
maybe your cors parameter wrong
This is the code in nodejs for to call the openweather API and print the result on the 127.0.0.7:8124 but do not understand why it does not work
var http = require('http');
function getData(city, res){
var urlData = 'http://api.openweathermap.org/data/2.5/weather?q='+city;
http.get(urlData, function(resi) {
var body = '';
resi.on('data', function(chunk) {
body += chunk;
});
resi.on('end', function() {
var dataResponse = JSON.parse(body)
res.write(dataResponse);
});
}).on('error', function(e) {
res.write("Got error: " + e);
});
}
// create http server
http.createServer(function (req, res) {
var query = require('url').parse(req.url).query;
var app = require('querystring').parse(query).city;
// content header
res.writeHead(200, {'Content-Type': 'text/plain'});
if(app){
console.log("ad: "+getData(app));
} else res.write("Use url:port?city=xxxx");
res.end();
}).listen(8124);
console.log('Server running at 8124');
this is the error
overflow#overflow-1015cx:~/Scrivania/nodeweather$ node app.js
Server running at 8124
ad: undefined
/home/overflow/Scrivania/nodeweather/app.js:15
res.write(dataResponse);
^
TypeError: Cannot call method 'write' of undefined
at IncomingMessage.<anonymous> (/home/overflow/Scrivania/nodeweather/app.js:15:13)
at IncomingMessage.EventEmitter.emit (events.js:117:20)
at _stream_readable.js:920:16
at process._tickCallback (node.js:415:13)
overflow#overflow-1015cx:~/Scrivania/nodeweather$
Why can not I return the result?
You are not passing the response object into getData
I believe it should look like this, but I have not tested it.
if(app){
console.log("ad: "+getData(app,res));
} else res.write("Use url:port?city=xxxx");\
If you read the error, its not telling you that you can't write, it's saying that you're trying to call write on a null object. If you trace the clues as to how res can be null, it should become clear.
Nodejs is async, res.end() is called before of res.write inside the http request.. so you need to use some "promise" tecnique or at least callbacks. However this code cannot work since you're trying to write a parsed json string, but the write method accepts only strings or buffer...moreover getData doesn't return nothing..so console.log("ad: "+getData(app,res,res.end)); prints an undefined variable.
maybe this code more fits your idea ( tested and working using "rome" ):
var http = require('http');
function getData(city, res,callback){
var urlData = 'http://api.openweathermap.org/data/2.5/weather?q='+city;
http.get(urlData, function(resi) {
var body = '';
resi.on('data', function(chunk) {
body += chunk;
});
resi.on('end', function() {
body=JSON.stringify(JSON.parse(body), null, 4)
res.write(body);
callback(body);
});
}).on('error', function(e) {
res.write("Got error: " + e);
callback("error");
});
}
// create http server
http.createServer(function (req, res) {
var query = require('url').parse(req.url).query;
var app = require('querystring').parse(query).city;
// content header
res.writeHead(200, {'Content-Type': 'text/plain'});
if(app){
getData(app,res,function (message) {
console.log("ad:",message);
res.end();
});
} else {
res.write("Use url:port?city=xxxx");
res.end("done");
}
}).listen(8124);
console.log('Server running at 8124');