Client receive json object to javascript - javascript

I want my server to send a JSON object to a javascript on the client's side. How can the client get the object into his javascript and not show the object on screen?
In my server :
app.get('/', function (req, res) {
res.send(jsonObj);
});
Thank you!

Using jquery i will show you a quick example of how things work:
Client
$.get('youserver.com/', {mydata: 'content'}, function(response){
//callback triggered when server responds
console.log(JSON.stringify(response));
});
Server
app.get('/', function (req, res) {
if(req.params.mydata === 'content'){
res.end("you sent content");
} else {
res.end("you sent something else");
}
});
Do you understand what i mean?

Try to use res.json() method
app.get('/', function (req, res) {
res.json(jsonObj);
});

Related

Why is data not received by Node.js through POST request?

So I have this functionality.
The client is sending data through jquery post function
$.post(currentURL + "/api/tables", newReservation,
function(data) {
if (data == true) {
alert("Yay! You are officially booked!")
}
if (data == false) {
alert("Sorry you are on the waitlist")
}
$('#reserve_name').val("");
$('#reserve_phone').val("");
$('#reserve_email').val("");
$('#reserve_uniqueID').val("");
});
Then Node.js is receiving it here
app.post("reserve/api/tables", function(req, res) {
var newentry = req.body;
console.log(newentry);
entries.push(newentry);
res.json(newentry);
});
However, console.log is giving me this error
jquery.js:9631 POST http://localhost:8080/api/tables 404 (Not Found)
Because you are doing the request to the url: http://localhost:8080/api/tables , but your server is waiting you at : "reserve/api/tables".
Try to target: http://localhost:8080/reserve/api/tables
your routing specifies a localhost:8080/reserve/api/tables,
remove the 'reserve' routing
You are missing leading slash in
app.post("reserve/api/tables", function(req, res) {
so it should be
app.post("/reserve/api/tables", function(req, res) {
or
app.post("/api/tables", function(req, res) {
as edited later

How to access the data sent via Jquery.getJSON from the server side?

I have the following $.getJSON request on the client side:
$.getJSON('/video/getToken', {classroomId: roomName}, cb);
On the server side:
router.route('/video/getToken')
.get(function(req, res) {
console.log(req.body);
});
The console.log is returning an empty object. Shouldn't the output be
{classroomId: roomName}?
You are doing a GET request, so there is no request body, instead you need to access the req.query:
Express 4.*
router.route('/video/getToken')
.get(function(req, res) {
console.log( req.query.classroomId );
});
Express 3.*
router.route('/video/getToken')
.get(function(req, res) {
console.log( req.query("classroomId") );
});

Returning HTML or JSON based on header type Nodejs

My nodeJS Api needs to return HTML or Json based on the header. If the header is:
Accept = application/json
The Api needs to return Json else my Api needs to return a HTML file.
this is the code I use on my routes:
var app = express();
app.use('/auth', require('./routes/Authenticate'));
In the Authenticate file I catch /login, and do the login stuff. if it succeeds I redirect to /users. In the /users I check for the Accept with an if statement:
router.get('/users', function(req,res){
if(req.get('Accept') === 'application/json'){
res.json({ success: true, user: req.user });
} else {
res.render("account/profile") //redirect to the file
}
});
This works(from this solution) but is there a better way? Because there are like 20 endpoints and the application is growing and this will be a mess for every endpoint.
you can split these actions into 2 functions. One to verify the content type and an other to doing your actions.
router.get('/users', checkIfJson, action);
function checkIfJson(req, res, next) {
if(!(req.get('Content-Type') === 'application/json')) {
res.render("account/profile");
return;
}
next();
}
function action(req, res) {
res.json({ success: true, user: req.user });
return;
}
If you write your code like that you can reuse your checkIfJson into other routes.
You can wrap router.get function with a custom function
router.wrappedGet = function (path, callback) {
router.get(path, function (req, res) {
if (req.get('Content-Type') === 'application/json') {
res.render = res.json;
}
callback(req, res);
})
};
Here's what I've doneā€”seems pretty straightforward.
router.get("/foo", HTML_ACCEPTED, (req, res) => res.send("<html><h1>baz</h1><p>qux</p></html>"))
router.get("/foo", JSON_ACCEPTED, (req, res) => res.json({foo: "bar"}))
Here's how those middlewares work.
function HTML_ACCEPTED (req, res, next) { return req.accepts("html") ? next() : next("route") }
function JSON_ACCEPTED (req, res, next) { return req.accepts("json") ? next() : next("route") }
Personally I think this is quite readable (and therefore maintainable).
$ curl localhost:5000/foo --header "Accept: text/html"
<html><h1>baz</h1><p>qux</p></html>
$ curl localhost:5000/foo --header "Accept: application/json"
{"foo":"bar"}
Notes:
I recommend putting the HTML routes before the JSON routes because some browsers will accept HTML or JSON, so they'll get whichever route is listed first. I'd expect API users to be capable of understanding and setting the Accept header, but I wouldn't expect that of browser users, so browsers get preference.
The last paragraph in ExpressJS Guide talks about next('route'). In short, next() skips to the next middleware in the same route while next('route') bails out of this route and tries the next one.
Here's the reference on req.accepts.

Node.js Express : How to redirect page after processing post request?

How to redirect to different page from post request ?
module.exports = function(app) {
app.post('/createStation', function(request, response){
response.redirect('/'); //This doesn't work, why and how to make this work
/*var stationDao = require('./server/stationDao.js');
stationDao.stationDao.createStation(request.body, function(status){
if(status.status == 'successful'){
response.redirect('/'); //This is what actually I wanted to do
}*/
});
});
};
Tried using next() as well,
app.post('/createStation', [function(request, response, next){
var stationDao = require('./server/stationDao.js');
stationDao.stationDao.createStation(request.body, function(status){
if(status.status == 'successful'){
next();
}
});
}, function abc(request, response){
console.log('I can see this');
response.redirect('/'); //This doesn't work still
}]);
It actually triggers the GET request but the page won't redirect.
Since I am new in node.js, any kind of suggestion for the above code would be appreciated.
I suggest you to leverage next, so something like
app.post('/', handlePostOnRoot);
app.post('/createStation', [
function(req, res, next){
next()
},
handlePostOnRoot
]);
On the subject: http://expressjs.com/guide/routing.html#route-handlers
EDIT based on comment:
I've just wrote a really basic server to test what I wrote:
var express = require('express');
var app = express();
app.post('/a', [function(req, res, next) {
next();
}, function(req, res) {
res.send('Hello World!');
}]);
var server = app.listen(3000, function () { console.log('listening'); });
This works for me, I would encourage you to run that and then curl -X POST http://localhost:3000/a, in my case I correctly got "Hello World!".
If this also works for you try to isolate your problem a bit more by removing some bits and pieces.
Not an expert in Angular, but from what I can find, the form won't automatically follow the / redirect after doing the POST. Instead, people recommend using Angulars $location.path('/'); to do a manual redirect after the form was submitted.

In an Express.js app, how to get the source POST data (the original string)?

I'm handling a POST request like so:
app.post('/somepage', function (req, res) {
var post_data = req.body;
});
Here, req.body already is a JavaScript object (I've tried console.log(req.body) and got [object Object] in the server's console). I would like to get the original POST data string that was sent with the HTTP request. Is that possible?
Note: I use this middle-ware:
app.use(express.json());
app.use(express.urlencoded());
Here's one solution that might work:
// ...
app.use(function(req, res, next) {
var buffer = '';
req.on('data', function(data) {
buffer += data.toString();
}).on('end', function() {
req.bodyraw = buffer;
});
next();
});
app.use(express.json());
app.use(express.urlencoded());
// ...
app.post('/somepage', function (req, res) {
var rawpost = req.bodyraw;
});
It should be safe since the json and urlencoded middleware add (data) event handlers immediately, but it would be better if the first middleware did pause() AND if the json and urlencoded middleware did resume() when seeing an explicitly paused stream -- this would guarantee no data could be lost.
You are searching for the 'body-parser' middleware. You have several options to get the body, including as the raw buffer or as text.
app.post('/somepage', function (req, res) {
var post_data = req.body.toString();
});

Categories

Resources