I have simple get route in my app.js file,
app.get('/crm/traveller/editForm/:id/:trv_id', passportConfig.isAuthenticated, function (req, res) {
console.log(">>>>>>>>>>>>>", req.params);
crm2.crmTravellerEditForm(req, res);
});
as per above code i have set two params by name of "id" and "trv_id",
i have console logged req.params
GET /crm/traveller/editForm/1102/121 200 7582.166 ms - -
>>>>>>>>>>>>> { id: '1102', trv_id: 'AxisBanner_file_1627882199782_Capture2.PNG' }
so when i enter "localhost:8083/crm/traveller/editForm/1102/121", expected params were id = 1102 and trv_id = 121 but in console.log i m getting some image in req.params.trv_id
Any help would be appreciated.
Thank you.
Related
Post method not working:
var user = {
"user4" : {
"name" : "mohit",
"password" : "password4",
"profession" : "teacher",
"id": 4
}
}
app.post('/addUser', function (req, res) {
// First read existing users.
fs.readFile( __dirname + "/" + "users.json", 'utf8', function (err, data) {
data = JSON.parse( data );
data["user4"] = user["user4"];
console.log( data );
res.end( JSON.stringify(data));
});
})
And I'm trying to access this by passing:
http://127.0.0.1:7000/addUser
Please help me through this.
The error is like this:
Cannot GET /addUser
The problem here is that you're trying to use the GET HTTP verb and not POST you could either:
Test this using a tool such as Postman (https://www.getpostman.com/) or use cURL to POST.
Change POST to GET and open it from within your browser.
Create a HTML Form element w/ the required fields and submit the form to the POST url.
Hope this helps.
A browser's URL bar will always make a GET request, not a POST. So you need to define your route as such :
app.get('/addUser', ....
instead of
app.post('/addUser', ....
I am new to node.js and I am trying to access json on my node.js server from a post request so I can send it to an API and feed it back to my front-end js file. I can see the json object, but I can't seem to access it(ex: req.body.name) after reading some documentation/stackoverflow posts.
Here is my post route from my server.js file, and packages:
var prettyjson = require('prettyjson');
var express = require('express');
var http = require('http');
var cors = require('cors');
var bodyParser = require('body-parser');
var app = express();
// create application/json parser
app.use(bodyParser.json());
// create application/x-www-form-urlencoded parser
app.use(bodyParser.urlencoded({
extended: true
}));
app.post('/', function(req, res) {
var test = req.body; //If I req.body.name here, it will return undefined
console.log(test);
});
Here is my front end map.js file post function and data:
var locations = [
{name:'Le Thai', coords:{lat:36.168743, lng:-115.139866}},
{name:'Atomic Liquors', coords:{lat:36.166782, lng:-115.13551}},
{name:'The Griffin', coords:{lat:36.168785, lng:-115.140329}},
{name:'Pizza Rock', coords:{lat:36.17182, lng:-115.142304}},
{name:'Mob Museum', coords:{lat:36.172815,lng:-115.141242}},
{name:'Joe Vicari’s Andiamo Italian Steakhouse', coords:{lat:36.169437, lng:-115.142903}},
{name:'eat', coords:{lat:36.166535, lng:-115.139067}},
{name:'Hugo’s Cellar', coords:{lat:36.169915, lng:-115.143861}},
{name:'Therapy', coords:{lat:36.169041, lng:-115.139829}},
{name:'Vegenation', coords:{lat:36.167401, lng:-115.139453}}
];
//convert array to JSON
var jsonStr = JSON.stringify(locations);
$.post('http://localhost:3000/', jsonStr, function(data){
//empty for now
},'json');
End goal: I want to be able to access my data like req.body.name. I tried using typeof on req.body, and it returns an object, however I can't seem to access this object. And I tried using JSON.parse, but realized req.body is already an object. I would like to serve this data to the Yelp API eventually.
Current output(per request) from console.log(req.body):
{ '{"name":"Le Thai","coords":{"lat":36.168743,"lng":-115.139866}},
{"name":"Atomic Liquors","coords":{"lat":36.166782,"lng":-115.13551}},
{"name":"The Griffin","coords":{"lat":36.168785,"lng":-115.140329}},
{"name":"Pizza Rock","coords":{"lat":36.17182,"lng":-115.142304}},
{"name":"Mob Museum","coords":{"lat":36.172815,"lng":-115.141242}},
{"name":"Joe Vicari’s Andiamo Italian Steakhouse","coords":
{"lat":36.169437,"lng":-115.142903}},{"name":"eat","coords":
{"lat":36.166535,"lng":-115.139067}},{"name":"Hugo’s Cellar","coords":
{"lat":36.169915,"lng":-115.143861}},{"name":"Therapy","coords":
{"lat":36.169041,"lng":-115.139829}},{"name":"Vegenation","coords":
{"lat":36.167401,"lng":-115.139453}}': '' }
You're using an array, so it will not be:
req.body.name
but e.g.
req.body[0].name
You probably want to iterate over the array that you get with .forEach or a for loop etc.
The problem is you're not telling the server you're sending it JSON, so it's not getting parsed. Also, as rsp pointed out, to access the first name, you'd want req.body[0].name, not req.body.name.
The dataType parameter on $.post isn't to tell the server what you're sending it, it's to tell jQuery what you're expecting back from the server. To tell the server what you're sending it, use $.ajax and the contentType option:
$.ajax({
url: 'http://localhost:3000/',
type: "POST",
contentType: "application/json", // <====
data: jsonStr,
success: function(data){
//empty for now
}
});
Now, the body-parser module sees the content type on the request, and parses it for you. So for instance, if I change your server file to do this:
app.post('/', function(req, res) {
req.body.forEach(function(entry, index) {
console.log(index, entry.name)
});
});
...then with the change above to the client code, I get this on the server console:
0 'Le Thai'
1 'Atomic Liquors'
2 'The Griffin'
3 'Pizza Rock'
4 'Mob Museum'
5 'Joe Vicari’s Andiamo Italian Steakhouse'
6 'eat'
7 'Hugo’s Cellar'
8 'Therapy'
9 'Vegenation'
For those getting an empty object in req.body
I had forgotten to set headers: {"Content-Type": "application/json"} in the request. Changing it solved the problem
Im new to Node.js and keep getting the Error: Route.get() requires callback functions but got a [object Undefined] error
and Ive checked out the following question and either dont understand or im still doing something wrong
Express routes: .get() requires callback functions but got a [object Object]
.get() requires callback functions but got a [object Undefined]
Error: Route.get() requires callback functions but got a [object Undefined]
Node Route.get() requires callback function but got a [object undefined]
my file structure is
server.js
routes/api/geolocations.js
routes/api/geolocations/regions.js
routes/api/geolocations/destination.js
ROOT: server.js
var geolocation = require('./routes/api/geolocation')(app);
app.get('/geolocation/', geolocation.delegate);
then I pass my data to routes/api/geolocations.js by using
geolocation.delegate(unparsedData);
from there I parse the data and send it down it's appropriate child routes.
PARENT: geolocations.js in my routes/api/geolocations.js
var destination = require('./geolocations/destination');
var region = require('./geolocations/region');
module.exports = function(app) {
return {
app.get('./geolocation/region', region.delegate);
app.get('./geolocation/destination', destination.delegate);
delegate: function(unparsedData, req, res) {
var data =[setup package for child states using unparsedData]
//HERE Id like to pass the new `data` to region or destination using the following
region.delegate(data);
//OR
destination.delegate(data);
CHILDREN: region.js / destination.js in routes/api/geolocations/regions.js or routes/api/geolocations/destination.js
module.exports = function(app) {
return {
delegate: function(data, req, res) {
...do stuff
}
}
}
UPDATE: I guess I dont know where to set up my routes, in server.js or if i can in geoloaction.js, does it matter, do need to do something like this in server.js?
var regions = require('./routes/api/geolocation/regions')([pass stuff here]);
geolocation.get('./routes/api/geolocation/regions', regions.delegate);
You should use express.js easy setup and run.
Simply download IntelliJ IDEA, find free version, then install. Then run the application and goto File->Setting->Plugin and search for NodeJS then install. Followed to this you need to Enable it. To do this goto File->Setting->Language & Frameworks->open arrow-> JavaScriptopen arrow->Libraries->Enable Node.js Core.
File Structure
routes/api/geolocations.js
routes/api/geolocations/regions.js
routes/api/geolocations/destination.js
You can have a look at the below code that might help you get started.
//------------------------------------------------------------------------
var express = require('express');
var router = express.Router();
var regions = require('../api/geolocations/regions');
var destination = require('../api/geolocations/destination');
//------------------------------------------------------------------------
//------------------------------------------------------------------------
/* geolocation.js */
router.get('/', function(req, res, next) {
var region_ext = regions.to_export;
var destin_ext = destination.to_export;
res.render('index', {
title: 'Geolocation',
region: region_ext,
destination:destin_ext
});
});
module.exports = router;
//------------------------------------------------------------------------
//------------------------------------------------------------------------
/* region.js */
var to_export = function () {
return 'this is from regions';
}
module.exports.to_export = to_export();
//------------------------------------------------------------------------
//------------------------------------------------------------------------
/* destination.js */
var to_export = function () {
return 'this is from destination';
}
module.exports.to_export = to_export();
//------------------------------------------------------------------------
//------------------------------------------------------------------------
//In app.js, just change
var routes = require('./routes/api/geolocations');
//------------------------------------------------------------------------
jfriend00 is right, You got a little mess there. Maybe you should consider make use of next(), since if you use it the other middlewares will have a chance of manipulating the request.
router.get('/:id', function(req, res, next){console.log(req.params.id)
request(
config.API_URL + "/v1/gallery/get?id=" + req.params.id,
function (err, response, body){
console.log('###BODY###',JSON.stringify(body));
console.log('###BODY###',JSON.stringify(body.data));
res.render('gallery', { user: req.session.user, gallery: body.data, title: 'Gallery', purchased: req.session.user.outlet ? (req.session.user.outlet.purchased || []) : [], config: config });
}
);
});
I'm trying to pass the request body's data field as the gallery for this template, but upon passing body.data, in the template it says my gallery argument is undefined. As you can see above, I then console logged the body and then its field. console.log(body) yields the following output:
###BODY### "{\"err\":null,\"data\": {\"_id\":\"5d955d7431d34f862a0dbd60\",\"owner
\":null,\"caption\":\"A suspected shooting at the Washington DC Navy Yard has sh
ut down parts of the city. This is the same location where a gunman killed 12 pe
ople in 2013. After an investigation search, authorities gave the \\\"all clear.
\\\"\",\"tags\":[\"dc\",\"navyyard\",\"shooting\",\"washington\"]...
I shortened the output, but as you can see, the data field is clearly there next to data.err. However, when I run console.log('###BODY###',JSON.stringify(body.data)), I am returned ###BODY### undefined. Can anyone explain this behavior please?
Replace this:
request(
config.API_URL + "/v1/gallery/get?id=" + req.params.id,
<callback>
);
With:
request({
url: config.API_URL + "/v1/gallery/get?id=" + req.params.id,
json: true
}, <callback>);
That will instruct request to automatically parse the response body as json (assuming you're using this request module, of course).
I know this looks repetitive, but it is a little bit different than the other question here.
I am using Node with the expressJS routing and passportJS login and in my login page I have a dropdown list to select a value that I want to pass along to my Angular script.
In my app.js I have:
var languages = [
{"lang": "English", "code": "en"},
{"lang": "Chinese", "code": "zh-cn"}
];
app.get('/', detectBrowser, routes.index);
app.get('/login', routes.login(isSameSubnet, languages));
index.js:
exports.index = function(req, res){
res.render('index', { login: 'Some String' });
};
exports.login = function(language) {
return function(req, res) {
res.render('login', { lang: language });
};
};
login.jade:
label.control-label Language
select.form-control
each val, index in lang
option(value= val.code)= val.lang
So how can I grab the value of the option tag back to my javascript and pass it to the next stage (AngularJS)?
I know how to get the information from the exports.index on the Angular side, but I don't know how to get the information I want and use it on this index function.
Thanks