How to return data response using express? - javascript

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 ??
});

Related

Node JS file transfer via Request Module

I am creating a node server to which files can be uploaded an then sent to a storage server which is also using node.
To do this i am using this method described on the Form-Data module page:
var formData = {
my_field: 'my_value',
my_file: fs.createReadStream(__dirname + '/unicycle.jpg'),
};
request.post({url:'http://service.com/upload', formData: formData}, function(err, httpResponse, body) {
if (err) {
return console.error('upload failed:', err);
}
console.log('Upload successful! Server responded with:', body);
});
My Problem is that when i try to write the file on the storage server it creates a text file with the content [object Object].
Here is my code:
main.js
var form = new formData();
form = {
'oldFileName': oldName,
'newFileName': newName,
'file': fs.createReadStream(FILEPATH),
};
request.post({url:'http://127.0.0.1:9001/upload', form: form}, function(err, httpResponse, body) {
if (err) {
return console.error('upload failed:', err);
}
});
storage.js
app.post('/upload', function(req,res){
//Filenames are displayed without problem
console.log(req.body.newFileName);
console.log(req.body.oldFileName);
fs.writeFile('./testing/' + req.body.newFileName, req.body.file, function(err) {
if(err) {
return console.log(err);
}
})
I'm sure I'm missing something really obvious, but I cant seem to get it to work.
You are passing formData in form option of request that changes the content to application/x-www-form-urlencodedinstead of multipart/form-data.
app.js
var form = {
'oldFileName': oldName,
'newFileName': newName,
'file': fs.createReadStream(FILEPATH),
};
request.post({url:'http://127.0.0.1:9001/upload', formData: form}, function(err, httpResponse, body) {
if (err) {
return console.error('upload failed:', err);
}
});
Also, to parse multipart/form-data, you have to use multer or similar library, body-parser doesn't work in that case. Please find following working storage.js code for saving file.
storage.js
var multer = require('multer')
var upload = multer({
storage: multer.diskStorage({
destination: function (req, file, cb) {
cb(null, './testing/');
},
filename: function (req, file, cb) {
cb(null, req.body.newFileName);
}
})
}).single('file');
app.post('/upload', function(req, res, next){
upload(req, res, function (err) {
if(err){
return res.send(err);
} else{
return res.send("Upload successfully");
}
});
});
Hope it helps you.
Alternatively, wrapping the [object Object] within a JSON.stringify() method should reveal the literal string content of the objects.
In my situation I was using the NodeJS Library for YouTube video uploads, following OAuth2.0 protocol.
Within this standard, you post your Client ID and Client Secret to authenticate your usage of the YouTube Data API.
In return, the server returns tokens, in the form of an Access Token and Refresh Token. These tokens are need to refresh the ability to use the API without expiry.
However, I was receiving (Object, object) in the terminal when requesting the 'tokens'....
Logger.log(Got the tokens:(token));
To rectify the problem and reveal the tokens in the terminal in a readable string format, I done the following...
Logger.log(Got the tokens: ${JSON.stringify(token)});
Now I can use the tokens accordingly.
//Note - ES6 backticks are used as string literals, but the backticks don't seem to be displaying in the parameters.

Cannot GET / DELETE Express.js

I have this script with which I'm trying to POST, GET and DELETE some stuff.
When I try POST or GET, the right messages are logged, but when I try DELETE, I get the following error:
Cannot GET /del_user
The URL I'm using is http://127.0.0.1:8081/del_user
What can be wrong in here?
var express = require('express');
var app = express();
// This responds with "Hello World" on the homepage
app.get('/', function (req, res) {
console.log("Got a GET request for the homepage");
res.send('Hello GET');
})
// This responds a POST request for the homepage
app.post('/', function (req, res) {
console.log("Got a POST request for the homepage");
res.send('Hello POST');
})
// This responds a DELETE request for the /del_user page.
app.delete('/del_user', function (req, res) {
console.log("Got a DELETE request for /del_user");
res.send('Hello DELETE');
})
// This responds a GET request for the /list_user page.
app.get('/list_user', function (req, res) {
console.log("Got a GET request for /list_user");
res.send('Page Listing');
})
// This responds a GET request for abcd, abxcd, ab123cd, and so on
app.get('/ab*cd', function(req, res) {
console.log("Got a GET request for /ab*cd");
res.send('Page Pattern Match');
})
var server = app.listen(8081, function () {
var host = server.address().address
var port = server.address().port
console.log("Example app listening at http://%s:%s", host, port)
})
I solved it by changing the app.delete to app.get and then placing the required remove statement inside the app.get. Something like this :-
app.get('/delete/:userId', (req, res) => {
Users.remove({ _id: req.params.userId }, (error, posts) => {
if (error) {
console.warn(error);
}
else {
data = posts
res.render("delete", {"data": data})
}
});
});
In your code you're binding the /del_user URL to the HTTP DELETE method.
So all you need to do is specify the DELETE method in your application or in Postman.
If you're not using it, it's an App in Google Chrome and you might want to download it, it makes your life a LOT easier ;)
Also, since the HTTP method is already declared to be DELETE, there is no need to specify it in the URL.
This is part of the RESTful working.
If you are using AJAX to try your code, you need to specify the method, which is delete.
$.ajax({
url: "http://127.0.0.1:8081/del_user",
type: "DELETE"
});

MYSQL + Node.JS Post Request Confusion

I am very new to networking and I have this code which, when I use a REST API like Postman, does exactly what I want it to do:
router.post('/', function(req,res,next){
var reqObj = req.body;
console.log(reqObj);
req.getConnection(function(err, conn){
if(err)
{
console.error('SQL Connection error: ', err);
return next(err);
}
else
{
var query = conn.query("INSERT INTO coordinates (id,lat,lon) VALUES(3,2,1);");
if(err)
{
console.error('SQL error: ', err);
return next(err);
}
res.json("Coordinates sent.");
}
})
} );
That is, it sends the query request to the MYSQL database. My question is, how do I do this without using Postman to send the POST request?
Thank you.
You can't unless you make a post request from within your application or something. If you don't intend on sending data, you can just make it a GET request by changing
router.post('/', function(req,res,next){
to
router.get('/', function(req,res,next){
Then you can just go to the relevant URL from your browser. If you're using chrome and you just wanna see the JSON data, I'd also recommend installing the JSONView chrome extension.
EDIT
Here's the example request using request-promise
var request = require('request-promise');
var objectData = {
name: 'Bruce',
alias: 'Batman'
};
var options = {
method: 'POST',
uri: 'http://your.api/endpoint/',
body: objectData,
json: true // Automatically stringifies the body to JSON
};
request(options).then(function(response){
// handle success response
}, function(error){
// handle error response
})

Get request doesn't work server side

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);

Bodyparser is incorrectly parsing JSON?

I'm using the body-parser NPM module with Express to parse json on my server, but for some reason, the JSON is showing up incorrectly on the server. Here is my server code:
...
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
...
app.route("/schedule")
.get(function(req, res) {
...
})
.post(function(req, res) {
var schedule = req.body.schedule;
console.log(req.body);
if(schedule) {
setSchedule(schedule);
res.status(200).end();
}
});
And my client code:
var schedule = {
entries: entries
};
var str = JSON.stringify(schedule);
console.log("Submitting schedule:",str);
post("/schedule", str)
.then((res) => {
this.completed(res.json);
})
.catch((res) => {
this.failed(res.text);
});
When I POST the data from the client, the client prints this:
Submitting schedule: {"entries":[1430014800000,1430055600000,1430104620000,1430146380000,1430194140000,1430236920000,1430283120000,1430326860000,1430371740000,1430416380000,1430460180000,1430505480000,1430548500000,1430594460000,1430636760000,1430683260000,1430725020000,1430772060000,1430813340000,1430860920000,1430901720000,1430949900000,1430990340000,1431039060000,1431079200000,1431128520000,1431168480000,1431218220000,1431258360000,1431308160000,1431349020000,1431398040000,1431440220000,1431487800000,1431531360000,1431577260000,1431622140000,1431666540000,1431712440000,1431755640000,1431802320000,1431844680000,1431891960000,1431933660000,1431981360000,1432022580000,1432070700000,1432111560000,1432159980000,1432200540000,1432249260000,1432289580000,1432338600000,1432378860000,1432428060000,1432468500000,1432517520000,1432558560000]}
Which appears to be valid JSON, but on the server, req.body is this:
{ '{"entries":': { '1430014800000,1430055600000,1430104620000,1430146380000,1430194140000,1430236920000,1430283120000,1430326860000,1430371740000,1430416380000,1430460180000,1430505480000,1430548500000,1430594460000,1430636760000,1430683260000,1430725020000,1430772060000,1430813340000,1430860920000,1430901720000,1430949900000,1430990340000,1431039060000,1431079200000,1431128520000,1431168480000,1431218220000,1431258360000,1431308160000,1431349020000,1431398040000,1431440220000,1431487800000,1431531360000,1431577260000,1431622140000,1431666540000,1431712440000,1431755640000,1431802320000,1431844680000,1431891960000,1431933660000,1431981360000,1432022580000,1432070700000,1432111560000,1432159980000,1432200540000,1432249260000,1432289580000,1432338600000,1432378860000,1432428060000,1432468500000,1432517520000,1432558560000]': '' } }
which is an object that's only key is {"entries": and the value for that key is an object that's only key is an array of timestamps that should be sent as the value to entries.
Any help would be greatly appreciated.
It appears the module I'm using for making requests (superagent) automatically stringifies data, so the issue went away when I stopped stopped using JSON.stringify.
In my case, the issue was that I was making the request from the front end using AngularJS, and the default POST format was set to url-encoded:
$httpProvider.defaults.headers.post = {'Content-type': 'application/x-www-form-urlencoded'};
By default, it's set to 'application/json', so I just removed this line, after which the JSON then resolved correctly.

Categories