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 ?
Related
I'm using NextJs and I'm trying to create a subscription form that sends data to MailChimp. However, I'm getting error which says
res.status is not a function
This file is inside my pages/api directory. What might be going wrong?
import { subscribe } from "../../lib/api";
const request = require("request");
export default async function subscribeWithEmail(req, res) {
const { email, js } = req.body;
const mcData = {
members: [
{
email_address: email,
status: "pending",
},
],
};
const mcDataPost = JSON.stringify(mcData);
const options = {
url: "https://us6.api.mailchimp.com/3.0/lists/SECRET",
method: "POST",
headers: {
Authorization: "auth APIKEY",
},
body: mcDataPost,
};
if (email) {
request(options, (err, res, body) => {
console.log(res);
if (err) {
res.json({ error: err });
} else {
if (js) {
res.status(200).send({ message: "yay" });
} else {
res.redirect("/");
}
}
});
} else {
res.status(404).send({ message: "Failed" });
}
// res.status(200).json(data);
return res.status(200);
}
You are shadowing your initial res variable.
// you have another res here, which has nothing to do with Next.js res, but it is overriding it
// So you need to rename it to something else, for example to "response"
request(options, (err, response, body) => {
console.log(response);
if (err) {
res.json({ error: err });
} else {
if (js) {
res.status(200).send({ message: "yay" });
} else {
res.redirect("/");
}
}
});
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 add comments functionality into my Sails.js blog application. However, I don't seem to write my controller action correctly.
When I submit the comment form, the page starts to reload, but does not finish reloading.
Here's my controller code:
const gravatar = require('gravatar');
module.exports = {
blog: (req, res) => {
Post.find({}).exec((err, posts) => {
if (err) {
res.send(500, { error: 'Database Error' });
}
res.view('all-posts', { posts });
});
},
singlePost: (req, res) => {
Post.findOneBySlug(req.params.slug).exec((err, post) => {
if (err) {
res.send(500, { error: 'Database Error' });
}
res.view('single-post', {
post,
gravatar: gravatar.url
});
});
},
addComment: (req, res) => {
const {
name, comment, email,
url, slug,
} = req.allParams();
Post.findOneBySlug(slug).exec((err, post) => {
if (err) {
return res.send(500, { error: 'Database Error' });
Comment.create({
body: comment, name, email, website: url
}).exec((error, comment) => {
if (error) {
return res.send(500, { error: 'Database Error' });
}
console.log(comment);
post.comments.addComment({slug, comment});
post.save();
res.redirect(`/${slug}`);
});
}
});
return false;
},
};
And here's my routes.js file:
module.exports.routes = {
'get /blog': 'BlogController.blog',
'get /:slug': 'BlogController.singlePost',
'post /:slug/new-comment': 'BlogController.addComment'
};
And this is my model Post.js
module.exports = {
identity: 'Post',
attributes: {
title: {
type: 'string',
required: true,
unique: true
},
body: {
type: 'string'
},
categories: {
type: 'string',
required: true
},
imageUrl: {
type: 'string'
},
comments: {
collection: 'Comment',
via: 'post'
},
slug: {
type: 'slug',
from: 'title',
blacklist: ['search', 'blog', 'contacts']
}
},
addComment: (options, cb) => {
Post.findOneBySlug(options.slug).exec((err, post) => {
if (err) return cb(err);
if (!post) return cb(new Error('Post not found.'));
post.comments.add(options.comment);
post.save(cb);
})
},
connection: 'mongodb'
};
So, when I submit the comment form on the /:slug page, nothing actually happens accept the page tries to reload. And in the database nothing gets saved as well.
The form parameters get sent from the form, so on the client side everything should be fine.
How how I approach this post request correctly?
You need to add return statement before each res.send(500, ...); call, because currently, in the case of the error, your code tries to send the response twice, and client doesn't get the response with the actual error:
if (err) {
return res.send(500, { error: 'Database Error' });
}
... rest code
I suspect, that the reason why nothing is saved in db is invalid parameters in request body.
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.
I'm using Watson API on my Node.js application. I successfully connected my application with the API, but I when I run my app I got this message:
"error invalid text representation"
This is my code :
var watson = require('watson-developer-cloud');
var conversation = watson.conversation({
url: 'https://gateway.watsonplatform.net/conversation-experimental/api',
username: '*********',
password: '*******',
version: 'v1',
version_date: '2016-07-01'
});
// req.body.text
conversation.message({
input: 'what is your name',
workspace_id: '***'
}, function(err, response) {
if (err) {
console.error(err);
} else {
console.log(JSON.stringify(response, null, 2));
}
});
your URL and version seems to be wrong..
Try this:
conversation.message({
input: {
text: 'what is your name'
},
workspace_id: '***'
}, function(err, response) {
if (err) {
console.error(err);
} else {
console.log(JSON.stringify(response, null, 2));
}
});
You have to add a 'text' to your JSON