I just wrote a ultrasimple nodejs backend with basic crud operations. However on the put statement i don't receive the body of my request:
app.put('/note-update/:id', function (req, res) {
var noteId = req.params.id;
console.log(req.body)
db.collection('notes').update({
_id: noteId
}, req.body, (err, result) => {
res.send(
(err === null) ? {
msg: req.body
} : {
msg: err
}
);
});
});
Here is the call i execute with ajax:
var note = {
_id: "599e660cbc845b4e2952715f",
name: "Genauer Detailbeschrieb",
note: "Ey-10"
}
$.ajax({
type: 'PUT',
url: '/note-update/599e660cbc845b4e2952715f',
dataType: 'JSON',
contentType: "application/json; charset=utf-8",
data: JSON.stringify(note)
})
as you can see i have a console.log(req.body) and all i get is {}
Are you using the bodyparser?
app.use(bodyParser.json());
Plz show more code for your node setup if it doesn't work.
Related
I followed the instructions on how to add the smart payment buttons from PayPal (https://developer.paypal.com/docs/checkout/integrate/) by using the SDK API. Everything works fine except that I can't redirect the buyer after the execution of the payment.
The JS code in the HTML page looks like this:
paypal.Buttons({
createOrder: function (data, actions) {
return actions.order.create({
purchase_units: [{
amount: {
value: price
}
}]
});
},
onApprove: async function (data, actions) {
return actions.order.capture().then(function (details) {
alert('success!');
return fetch('/paypal-transaction-complete', {
method: 'post',
headers: {
'content-type': 'application/json'
},
body: JSON.stringify({
orderID: data.orderID,
})
});
});
}
}).render('#paypal-button-container');
On the server side I execute it with async functions and wait for the promise by using the arrow functions:
app.post('/paypal-transaction-complete', function (req, res) {
paypalRequestHandler.handleRequest(req, res)
.then(() => {
res.redirect('/'); // not working
}).catch(err => {
console.log(err);
res.sendStatus(500);
});
});
I'm wondering why it's not redirecting, I can do stuff like console.log() but it just won't redirect the buyer.
To answer my own question: after getting the promise on the server side, a response code should be returned to the client, then on the client side the location of the page can be changed. So in my case it looks like this on the server side:
app.post('/paypal-transaction-complete', function (req, res) {
paypalRequestHandler.handleRequest(req, res)
.then(() => {
res.sendStatus(200);
}).catch(err => {
console.log(err);
res.sendStatus(500);
});
});
On the client side:
paypal.Buttons({
createOrder: function (data, actions) {
return actions.order.create({
purchase_units: [{
amount: {
value: price
}
}]
});
},
onApprove: async function (data, actions) {
return actions.order.capture().then(function (details) {
alert('success!');
const responsePromise = fetch('/paypal-transaction-complete', {
method: 'post',
headers: {
'content-type': 'application/json'
},
body: JSON.stringify({
orderID: data.orderID,
})
});
responsePromise.then(function (responseFromServer) {
if(responseFromServer.status === 200) {
location.href = 'success_page';
} else {
alert('smth went wrong');
location.href = '/';
})
}
});
});
}
}).render('#paypal-button-container');
Before Asking this Question I have referred the below but didn't help me
Passport.js & Facebook Graph API
Retrieving photo from Facebook using passport-facebook
https://www.hitchhq.com/facebook-graph-api/docs/facebook-authentication
http://tech.bigstylist.com/index.php/2017/08/12/search-facebook-graph-api-nodejs/
How to use Facebook Graph API after authenticating with Passport.js facebook strategy?
enter link description here
And Some posts say to use passport-facebook-token But I don't want to use as I want to extend the existing functionality of my application with passport-facebook only
Problem Statement
Currently, I am using passport-facebook for authentication which works perfectly and Now I want to extend the functionality to use Facebook Graph API to get the photos of the users who log in to my application
So use the Facebook Graph API to get the user photos I have to make below call using request module in Node JS, The body part will return me the expected result
var request = require("request");
var options = {
method: 'GET',
url: 'https://graph.facebook.com/me/photos/',
qs: {
access_token: 'EBBCEdEose0cBADwb5mOEGISFzPwrsUCrXwRWhO87aXB9KsVJlgSLc19IdX9D9AKU7OD5SdFOqPXW3eLm8J3HltZC14VexdMsEDW35LDWASdVDNGp5brFERBETsIvxXJIFXo7QSum5apHXeRyQk7c2PQljmf5WHObZAwXVzYjqPd4lziKTUK48Wfrw5HPwZD'
},
headers: {
'content-type': 'application/json'
}
};
request(options, function (error, response, body) {
if (error) throw new Error(error);
console.log(body);
});
But now I wanted to create my custom express GET API when I call that I use should be getting the above body response,
like GET : /graph/photos
app.get('/graph/photos', function (req, res) {
res.send(body)//Here I wanted to get the same response as of the request module above
});
But I have the below challenges
Getting the access_token from the passport-facebook and pass that to the request module
If the user is not authenticated thrown an error in the API response
But I could able to proceed somewhat with below approach, I have followed the tutorial from
https://github.com/scotch-io/easy-node-authentication/tree/linking
app.get('/graph/photos', isLoggedIn, function (req, res) {
var hsResponse = request({
url: 'https://graph.facebook.com/me/photos',
method: 'GET',
qs: {
"access_token": req.user.facebook.token
},
}, function (error, response, body) {
res.setHeader('Content-Type', 'application/json');
res.send(body);
});
});
But the problem I am facing is every time call the API /graph/photos/, It will try to redirect to check whether the user is logged in hence I won't be directly able to use in Angular Service and getting below error
Error
Failed to load http://localhost:3000/graph/photos: Redirect from 'http://someurl' to 'http://someurl' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access.
try this...
I wrote the function for my project,you just customize....
// facebook login
exports.facebookLogin = function(req, res) {
var fields = config.loginFaceBook.fbFields;
var accessTokenUrl = config.loginFaceBook.fbAccessTokenUrl;
var graphApiUrl = config.loginFaceBook.fbGraphApiUrl + fields.join(',');
var params = {
code: req.body.code,
client_id: req.body.clientId,
client_secret: config.loginFaceBook.fbClientSecret,
redirect_uri: req.body.redirectUri
};
// Step 1. Exchange authorization code for access token.
request.get({
url: accessTokenUrl,
qs: params,
json: true
}, function(err, response, accessToken) {
console.log('Exchange authorization code err::', err);
console.log('Exchange authorization code accessToken::', accessToken);
if (response.statusCode !== 200) {
return res.status(500).send({
message: accessToken.error.message
});
}
// Step 2. Retrieve profile information about the current user.
request.get({
url: graphApiUrl,
qs: {
access_token: accessToken.access_token,
fields: fields.join(',')
},
json: true
}, function(err, response, profile) {
console.log('Retrieve profile information err::', err);
console.log('Retrieve profile information::', profile);
if (response.statusCode !== 200) {
return res.status(500).send({
message: profile.error.message
});
}
if (req.header('Authorization')) {
console.log('req header Authorization', req.header('Authorization'));
} else {
var socialEmail;
if (profile.email) {
socialEmail = profile.email;
} else {
socialEmail = profile.id + '#facebook.com';
}
// Step 3. Create a new user account or return an existing one.
UserModel.findOne({
email: socialEmail
}, function(err, existingUser) {
if (existingUser) {
AppClientModel.findOne({
_id: config.auth.clientId
}, function(err, client) {
if (!err) {
var refreshToken = generateToken(existingUser, client, config.secrets.refreshToken);
var rspTokens = {};
rspTokens.access_token = generateToken(existingUser, client, config.secrets.accessToken, config.token.expiresInMinutes);
var encryptedRefToken = cryptography.encrypt(refreshToken);
var token = {
clientId: client._id,
refreshToken: refreshToken
};
UserModel.update({
_id: existingUser._id
}, {
$push: {
'tokens': token
}
}, function(err, numAffected) {
if (err) {
console.log(err);
sendRsp(res, 400, err);
}
res.cookie("staffing_refresh_token", encryptedRefToken);
sendRsp(res, 200, 'Success', rspTokens);
});
}
});
}
if (!existingUser) {
var userName = profile.first_name + ' ' + profile.last_name;
var newUser = new UserModel({
name: userName,
img_url: 'https://graph.facebook.com/' + profile.id + '/picture?type=large',
provider: 2, //2: 'FB'
fb_id: profile.id,
email_verified_token_generated: Date.now()
});
log.info("newUser", newUser);
newUser.save(function(err, user) {
if (!err) {
var refreshToken = generateToken(user, client, config.secrets.refreshToken);
var rspTokens = {};
rspTokens.access_token = generateToken(user, client, config.secrets.accessToken, config.token.expiresInMinutes);
var encryptedRefToken = cryptography.encrypt(refreshToken);
var token = {
clientId: client._id,
refreshToken: refreshToken
};
UserModel.update({
_id: user._id
}, {
$push: {
'tokens': token
}
}, function(err, numAffected) {
if (err) {
console.log(err);
sendRsp(res, 400, err);
}
res.cookie("staffing_refresh_token", encryptedRefToken);
sendRsp(res, 200, 'Success', rspTokens);
});
} else {
if (err.code == 11000) {
return sendRsp(res, 409, "User already exists");
} else {
return sendRsp(res, 500, "User create error");
}
}
});
}
});
}
});
});
};
I'm trying to send a message to a facebook user, using POST method :
Here is the function :
router.post('/post/message/:userid', function (req, res, next) {
messageData = {
recipient: {id: req.params.userid},
message: {text:req.body.text}
}
console.log( messageData );
request({
url: 'https://graph.facebook.com/v2.6/'+ pageid +'/messages',
qs: {access_token: token_raw},
method: 'POST',
json: messageData
}, function (error, response, body) {
if (error) {
console.log('Error sending message: ', error);
} else if (response.body.error) {
console.log('Error: ', response.body.error);
}
});
});
But then here are the console logs :
{ recipient: { id: '**ClientID**' },
message: { text: 'hello' } }
type: 'OAuthException',
Error: { message: '(#100) No matching user found',
code: 100,
fbtrace_id: 'FlDy9Ypfen8' }
While "ClientID" is actually a valid userID.
Any idea ?
When I execute this function from something like Postman:
router.get('/db', function(req, res, next) {
tune.find({}, function (err, results) {
res.json(results);
});
});
My database returns this:
[{"_id":"56f30425ba97bb301fe6ab1a","__v":0},
{"_id":"56f30514f9b7ea3b1f1fd9f7","__v":0},
{"_id":"56f306bb9c8203451f2cc58a","__v":0},
{"_id":"56f306ca9c8203451f2cc58b","__v":0},
{"_id":"56f306e99c8203451f2cc58c","__v":0},
{"_id":"56f33d43b64d540b208b6c3c","__v":0}]
My mongoose schema:
var Schema = mongoose.Schema;
var track = new Schema({
title: String,
artist: String,
genre: String
});
var tune = mongoose.model('tune', track);
My post:
router.post('/db', function(req, res, next) {
var tune1 = new tune(req.body);
tune1.save(function (err) {
if (err) { console.log('error!');}
else {
res.json({message: 'Track successfully posted'});
}
});
});
Request Post:
app.use('/users', userRoutes);
var options = { method: 'POST',
url: 'http://localhost:3000/users/db',
headers:
{ 'content-type': 'application/x-www-form-urlencoded',
'postman-token': '',
'cache-control': 'no-cache' },
form: { title: '000000', artist: 'blah blah', genre: 'rap' } };
request(options, function (error, response, body) {
if (error) throw new Error(error);
console.log(body);
});
When I do a post command from Postman I get a successful post message. Is it just the way I am returning the JSON? I want to be able to see title, artist, and genre for every post in the DB.
Thanks
In this instance, Mongoose simply isn't saving what you're expecting. Try taking a look at req.body and tune1 in a debugger to make sure you're getting the expected result.
It might also help to set strict to 'throw' in your schema, just so we get an error back when we attempt to save an invalid tune:
var track = new Schema({
title: String,
artist: String,
genre: String
}, {
strict: 'throw'
});
I am using a RESTful web service to make a to do list app. I am able to make a GET request and retrieve all of my todos but I don't know how to print them onto my webpage.
Here is the part responsible for making the GET request:
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
request({
url: url, //URL to hit
qs: {from: 'blog example', time: +new Date()}, //Query string data
method: 'GET', //Specify the method
headers: { //We can define headers too
'Content-Type': 'MyContentType',
'Custom-Header': 'Custom Value'
}
}, function(error, response, body){
if(error) {
console.log(error);
} else {
console.log(response.statusCode, body);
}
});
I am using jade instead of HTML. Running the above code outputs the following into my console.
200 '[{"id":"4017cd30-164e-11e5-9a6f-f52ee4e229e9","data":{"name":"Hello
world"}},{"id":"e0591080-1656-11e5-955e-271a38c26f32","data":{"name":"get
groceries"}},{"id":"e97fe620-1656-11e5-955e-271a38c26f32","data":
{"name":"deposit cheque"}}]'
This is what I need to print to webpage. Thanks.
router.get('/', function(req, res, next) {
request({
url: url, //URL to hit
qs: {from: 'blog example', time: +new Date()}, //Query string data
method: 'GET', //Specify the method
headers: { //We can define headers too
'Content-Type': 'MyContentType',
'Custom-Header': 'Custom Value'
}
}, function(error, response, body){
if(error) {
res.render('index', { title: 'Express', data: []});
} else {
res.render('index', { title: 'Express', data: body });
}
});
In you jade file:
ul
for item in data
li= item
else
li sorry, no items!