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', ....
Related
I have code in Nodejs as backend and Angular as frontend.
I want to receive and send data by one endpoint and based on that data from server toggle a button. Toggling is working now but I want when I sign out from the dashboard next time that I log in I could see the value of the key is based on the value from the database.
For example, first, it's SET after clicking it changed to CLEAR and I sign out from the dashboard. When next time I log in I want to see the CLEAR label on my button.
These are codes for several parts of the app:
Angular Service
this.setUserFeatured = function(id, setFeatured) {
return $http.put('/admin/v2/users/' + id + '/featured', { setFeatured: setFeatured })
.then(returnedDataOrError);
};
Angular Controller
function updateFeaturedButtonLabel() {
$scope.featuredButtonLabel = $scope.user.setFeatured ? "Clear Featured" : "Set Featured";
}
function toggleFeatured () {
$scope.user.setFeatured = !$scope.user.setFeatured;
UserService.setUserFeatured($stateParams.id, $scope.user.setFeatured)
updateFeaturedButtonLabel();
};
Html File
<a class="btn btn-info" ng-click="toggleFeatured()" ng-class="{on:user.setFeatured}">{{featuredButtonLabel}}</a>
Server Controller
function addFeaturedUser(req: $Request, res: $Response, next: NextFunction) {
const schema = Joi.object().keys(_.pick(validate, ['userId', 'setFeatured']));
const queryParams = { userId: req.params.id };
if (!req.params.id) {
return new errors.BadRequest('userId is not specified');
}
return validate.validate(queryParams, schema)
.then(validatedParams =>
userService5.updateUserLabel(validatedParams.userId, req.body.setFeatured))
.then(result => res.json(result))
.catch(next);
}
router.put('/users/:id/featured', addFeaturedUser);
And updateUserLabel is a function that handling the connection to the database and retrieving the data.
I just wonder how can I use the data from the server to change the label of the button?
true/false for the setting the button is coming from the .then(result => res.json(result))
Thanks in advance for help
For your question, I suppose you are asking how to use the response object returned in
$http.put().then(function(response){})
You can find the structure of response object in following document.
https://docs.angularjs.org/api/ng/service/$http
To access the data returned from server:
$http.put().then(function(response){response.data})
which corresponds to what your server sends.
Besides, the toggleFeatured function should be add to $scope object.
Otherwise, ng-click can't trigger that function in html template.
Hope it helps.
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
I recently started programming on nodeJs.
I am using Angular JS, resource to call API's as
demoApp.factory('class', function ($resource) {
return $resource('/class/:classId', { classId: '#_classId' }, {
update: { method: 'PUT' }
});
});
And in Controller, I have delete method as;
// The class object, e {classId: 1, className: "Pro"}
$scope.deleteClass = function (class) {
var deleteObj = new Class();
deleteObj.classId = class.classId;
deleteObj.$delete({classId : deleteObj.classId}, function() {
growl.success("Class deleted successfully.");
$location.path('/');
},function () {
growl.error("Error while deleting Class.");
}
);
};
Using browser, I verified call goes to :
http://localhost:3000/class/1
Now in node Js, How should I extract value from Url,
In server.js
app.use('/class', classController.getApi);
In classController.js
exports.getApi = function(req, resp){
switch(req.method) {
case 'DELETE':
if (req) {
// how to extract 1 from url.
}
else {
httpMsgs.show404(req, resp);
}
break;
I have tried ,
console.log(req.params);
console.log(req.query);
But no luck.
I am seeing
console.log(req._parsedUrl);
query: null,
pathname: '/class/1',
path: '/class/1',
Any help appreciated.
This should be a get call right ? You can use angular $http service, with method as get. Replace your app.use('/class') with app.get('/class', function). Then you can use req.param('classId') to retrieve data. I think it should work.
Try updating your app.use to app.use('/class/:classId'), then try req.params.classId
Try using req.hostname as in:
`http://host/path'
Check this answer.
Tldr;
var url = require('url');
var url_parts = url.parse(request.url, true);
var query = url_parts.query;
Also read the docs on node url.
I'm making an app that allows user to like and comment on other user post. I'm using Parse as my backend. I'm able to notified user everytime their post liked or commented. However if current user like or comment on their own post this current user still notified. How can I prevent this?
Here is the js code that I use:
Parse.Cloud.afterSave('Likes', function(request) {
// read pointer async
request.object.get("likedPost").fetch().then(function(like){
// 'post' is the commentedPost object here
var liker = like.get('createdBy');
// proceed with the rest of your code - unchanged
var query = new Parse.Query(Parse.Installation);
query.equalTo('jooveUser', liker);
Parse.Push.send({
where: query, // Set our Installation query.
data: {
alert: message = request.user.get('username') + ' liked your post',
badge: "Increment",
sound: "facebook_pop.mp3",
t : "l",
lid : request.object.id,
pid: request.object.get('likedPostId'),
lu : request.user.get('username'),
ca : request.object.createdAt,
pf : request.user.get('profilePicture')
}
}, {
success: function() {
console.log("push sent")
},
error: function(err) {
console.log("push not sent");
}
});
});
});
If I understand the context of where this code is correctly,
I recommend checking
if request.user.get("username") != Parse.CurrentUser.get("username")
Before sending out the push notification
Where is your cloud function being called from? If you're calling it from your ios code, then before you call the cloud code function, just prelude it with something like this:
if (PFUser.currentUser?.valueForKey("userName") as! String) != (parseUser.valueForKey("userName") as! String)
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).