How to print contents on webpage from RESTful web service - node.js

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!

Related

Auth0 sync userinfo

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?

How to redirect after an execution of a paypal payment?

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');

Back-end API receiving empty request body when making request from front-end

I am building Web application on my localhost.
The front-end is Reactjs framework, running in localhost:3000
The back-end is nodejs + Express, running in localhost:4000
Now, I have created the API below:
router.post('/register', function (req, res) {
console.log(req.body); // {}, why it is empty?
// create new instance, save it to database
User.create(req.body).then(function () {
res.send('success');
});
});
The front-end part is:
handleSubmit = (e) => {
e.preventDefault();
this.props.form.validateFieldsAndScroll((err, values) => {
if (!err) {
console.log('Received values of form: ', values); // value is not empty, I have tested! So we did send something to the API
const input = JSON.stringify({
username: values.username,
password: values.password,
});
console.log(input);
$.ajax({
url: `${API_ROOT}/register`,
method: 'POST',
data: JSON.stringify({
username: values.username,
password: values.password,
}),
}).then((response) => {
if (response === 'success') {
this.props.history.push('/login');
} else {
console.log('do not jump');
}
});
}
});
}
I have tested the API by the postman, I can add users to MongoDB, so the API is good.
I have console.log what I sent to API, it is not empty, however, backend API receive d empty request body. I have already fixed the "Access-Control-Allow-Origin" issue, so I think I do send something to the API, but backend API received empty request body.
If you add a content type header saying what type the body of the request is it should work as expected.
$.ajax({
url: `${API_ROOT}/register`,
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
data: JSON.stringify({
username: values.username,
password: values.password,
})
})

CRUD nodejs/express server: app.put req.body is empty

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.

Mongo .get returning junk

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'
});

Resources