i can't figure out what to place in exchange of the JSON.stringify syntax in the body parameter. It is returning a SyntaxError with a code of 800A03EA
const request = require('request');
const username = 'myUserName';
const password = 'myPassword';
const options = {
method: 'POST',
url: 'https://siteToPostTo.com/api/v1/statuses',
auth: {
user: username,
password: password
},
body: JSON.stringify({
status: 'automated message to post'
})
};
request(options, function(err, res, body) {
if (err) {
console.dir(err);
return;
}
console.log('headers', res.headers);
console.log('status code', res.statusCode);
console.log(body);
});
Nothing. Instead, add
json: true to your options and don't attempt any stringification. request() will do the magic for you.
const request = require('request');
const username = 'myUserName';
const password = 'myPassword';
const options = {
method: 'POST',
url: 'https://siteToPostTo.com/api/v1/statuses',
auth: {
user: username,
password: password
},
json: true,
body: {
status: 'automated message to post'
}
};
request(options, function(err, res, body) {
if (err) {
console.dir(err);
return;
}
console.log('headers', res.headers);
console.log('status code', res.statusCode);
console.log(body);
});
Related
I'm trying to sync my auth0 userinfo with my local database:
userRouter.get("/sync", validateAccessToken, (req, res) => {
var request = require("request");
var usertoken;
var options = { method: 'POST',
url: 'https://MYDOMAN.eu.auth0.com/oauth/token',
headers: { 'content-type': 'application/json' },
body: '{"client_id":"myclienttoken","client_secret":"myclientsecret","audience":"https://MYDOMAIN.eu.auth0.com/api/v2/","grant_type":"client_credentials"}' };
request(options, function (error, response, body) {
if (error) throw new Error(error);
usertoken = body;
console.log(body);
});
var auth0options = {
method: "GET",
url: "https://MYDOMAIN.eu.auth0.com/api/v2/users",
params: {id: 'email:"testuser"', search_engine: 'v3'},
headers: {
"content-type": "application/json",
authorization: `Bearer` + usertoken.access_token,
},
};
axios.request(auth0options).then(function (response) {
console.log("RES DATA: ", response.data);
})
.catch(function (error) {
console.error(error);
});
console.log("called");
res.status(200).json("message");
});
The following line, results in a error:
authorization: Bearer + usertoken.access_token,
"Cannot read properties of Undefined (reading 'access_token)"
But I don't get the userinfo when calling the auth0 api with that token.
I'm using the audience from the Auth0 Management API ex:
https://MYDOMAIN.eu.auth0.com/api/v2/
And not the audience from my own API, as I have read that's the correct way:
https://mydomain
Any ideas on what I'm doing wrong?
I want to create a REST API which allows a requestor to PATCH multipart/form-data containing a file. The server extracts the file and sends by SMTP as an email attachment. I have the following code:
const nodemailer = require('nodemailer');
const smtpTransport = require('nodemailer-smtp-transport');
const username = 'email account'
const password = 'email password'
const smtpHost = 'mailhog'
const smtpPort = 1025
module.exports.endpoint = (event, context, callback) => {
const mailOptions = {
from: 'wat#address.com',
to: 'inbox#address.com',
subject: 'Here is a file',
text: 'Please see attached'
};
const transporter = nodemailer.createTransport(smtpTransport({
host: smtpHost,
port: smtpPort,
secure: false,
auth: {
user: username,
pass: password
}
}));
transporter.sendMail(mailOptions, function (error, info) {
if (error) {
const response = {
statusCode: 500,
body: JSON.stringify({
error: error.message,
}),
};
callback(null, response);
}
const response = {
statusCode: 202,
headers: {
"Access-Control-Allow-Origin": "*"
},
body: "Accepted",
};
callback(null, response);
});
}
Is there a good way of doing this?
Using aws-lambda-multipart-parser I was able to do this quite simply:
use strict';
const multipart = require('aws-lambda-multipart-parser');
const nodemailer = require('nodemailer');
const smtpTransport = require('nodemailer-smtp-transport');
const username = 'email account'
const password = 'email password'
const smtpHost = 'mailhog'
const smtpPort = 1025
module.exports.endpoint = (event, context, callback) => {
const file = multipart.parse(event, true).file;
const mailOptions = {
from: 'wat#address.com',
to: 'inbox#address.com',
subject: 'Here is a file',
text: 'Please see attached',
attachments: [
{
filename: file.filename,
content: file.content,
contentType: 'image/png'
}
]
};
const transporter = nodemailer.createTransport(smtpTransport({
host: smtpHost,
port: smtpPort,
secure: false,
auth: {
user: username,
pass: password
}
}));
transporter.sendMail(mailOptions, function (error, info) {
if (error) {
const response = {
statusCode: 500,
body: JSON.stringify({
error: error.message,
}),
};
callback(null, response);
}
const response = {
statusCode: 202,
headers: {
"Access-Control-Allow-Origin": "*"
},
body: "Accepted",
};
callback(null, response);
}
I need to be able to save the token returned by the POST request so I can decode it and send it back with my other requests. I can only console log the token but could find no way of saving it to a variable. How do I go about doing this? Am I thinking of this problem all wrong?
const request = require('request');
const options = { method: 'POST',
url: process.env.AUTH_URL,
headers:
{ 'cache-control': 'no-cache',
'content-type': 'application/json',
api_key: process.env.API_KEY,
client_secret: process.env.CLIENT_SECRET,
client_id: process.env.CLIENT_ID },
body: { userName: process.env.USERNAME, userPassword: process.env.PASSWORD },
json: true };
async function authenticate(options) {
try{
console.log('inside try');
const reqToken = await request(options, function (error, response, body) {
if (error) throw new Error(error);
console.log(body.token);
});
} catch(error) {
throw(error);
}
}
Either promisify the request or simply use axios which supports promise out of the box.
async function authenticate(options) {
try {
console.log("inside try");
const reqToken = await new Promise((res, rej) => {
request(options, function(error, response, body) {
if (error) rej(error);
res(body.token);
});
});
} catch (error) {
throw error;
}
}
OR using axios:
async function authenticate(options) {
try {
console.log("inside try");
const { data:{ token } } = await axios(options);
} catch (error) {
throw error;
}
}
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 using http.post node.js to post to https://api.mmitnetwork.com/Token to get an access Token.
How do I take the reponse I get back and set the state?
var App = React.createClass ({
getInitialState() {
return {
token: ''
}
},
componentDidMount() {
var _this = this;
var request = http.post('https://api.mmitnetwork.com/Token', {grant_type: 'password', username: 'myusername', password: 'mypassword'}, function(response) {
console.log(response.statusCode);
response.on('data', function(chunk) {
console.log('BODY: ' + chunk);
_this.setState({
token: response.chunk.access_token
})
});
})
request.on('error', function(err) {
console.error(err.message);
})
},
render() {
{this.state.token}
}