get data to index.js(modul.export) - node.js

I am new in Node.js.
I'm trying to figure out how I can get values from file auth.js to index.js with module.export.
File auth.js:
const request = require('request');
request.post(
'http://192.167.1.118/api/v1/auth/request',
{
form: {
application: 'car',
user: 'car',
},
},
(error, res, body) => {
if (error) {
console.error(error);
return;
}
//console.log(`statusCode: ${res.statusCode}`)
body = JSON.parse(body);
//console.log(body);
}
);
module.exports.request = request;
File index.js:
const aaa = require('./auth');
console.log(aaa.request);

You may need to convert that callback based request into promise.
Make an individual function which returns promise of you api response.
auth.js
const request = require('request');
const sendRequest = () =>
new Promise((resolve, reject) =>
request.post(
'http://192.167.1.118/api/v1/auth/request',
{
form: {
application: 'car',
user: 'car',
},
},
(error, res, body) => {
if (error) {
reject(error);
}
body = JSON.parse(body);
resolve(body);
}
)
);
module.exports.request = sendRequest;
index.js
const { request } = require('./auth');
request().then(body => {
console.log(body);
}).catch(error => {
console.error(error); // <- error
});

Related

How can I fix my code to make it send the json data as a response to postman's GET requests?

The data I am receiving through the code is outputting to the cmd through console.log but I can't seem to figure out how to make that same data available for GET requests from postman. Thank you
const express = require('express');
const app = express();
const PORT = 5000;
const apicall = require('./apicall');
const request = require('request');
app.get('/', (req, res) => {
res.send("Hello world!")
});
app.get('/getinfo', (req, res, body) => {
const getToken = (url, callback) => {
const options = {
url: process.env.GET_TOKEN,
json: true,
body: {
client_id: process.env.CLIENT_ID,
client_secret: process.env.CLIENT_SECRET,
grant_type: 'client_credentials'
}
};
request.post(options, (err, res, body) => {
if(err) {
return console.log(err)
}
console.log(`Status: ${res.statusCode}`)
console.log(body);
callback(res);
});
}
var AT = '';
var info = '';
getToken(process.env.GET_TOKEN, (res) => {
AT = res.body.access_token;
return AT;
});
const getGames = (url, accessToken, callback) => {
const gameOptions = {
url: process.env.GET_GAMES,
method: 'GET',
headers: {
'Client-ID': process.env.CLIENT_ID,
'Authorization': 'Bearer ' + accessToken
}
};
request.get(gameOptions, (err, res, body) => {
if(err) {
return console.log(err);
}
let x = '';
console.log(`Status: ${res.statusCode}`);
console.log(JSON.parse(body));
//res.send(parsed);
//req.body.getinfo = JSON.parse(body);
})
}
setTimeout(() => {
getGames(process.env.GET_GAMES, AT, (response) => {
});
}, 1000);
//res.send(JSON.parse(body));
});
app.listen(PORT, () => {
console.log(`Example app listening on port ${PORT}`);
});
You use res.send in the callback of a request.get. But in that context, res is the incoming response from the API that you call, not the outgoing response created by your app. Only the outgoing response contains a send method.
To keep both separate, use different names:
app.get("/getinfo", function(req, res) {
request.get(..., function(err, incoming_res, body) {
res.json(JSON.parse(body));
});
});
res.send is a part of express. If the res.send that's failing is in request.get then that's because it's not a part of express.
From the docs for request it says that the response argument will be an instance of http.IncomingMessage. That should mean you can simply use res.end
Edit:
#HeikoTheißen is right. There is no res.end.
But this could be handled in a different way. If we can wrap the get request inside a promise, then we could resolve the promise with whatever needs to be sent from the get request.
An example:
const result = await new Promise((resolve) => {
request(gameOptions, function (error, response, body) {
resolve ({status : 'A Ok!'}) // <--- send response here
}
}
console.log ("result is ", result) // <-- Object {status : 'A Ok!'}
You just pipe it to the response like so .pipe(res)
const express = require('express');
const app = express();
const PORT = 5000;
const apicall = require('./apicall');
const request = require('request');
app.get('/', (req, res) => {
res.send("Hello world!")
});
app.get('/ne2', (req, res) => {
//res.send('This is the new endpoint');
apicall.getCall;
});
app.get('/getinfo', (req, res, body) => {
const getToken = (url, callback) => {
const options = {
url: process.env.GET_TOKEN,
json: true,
body: {
client_id: process.env.CLIENT_ID,
client_secret: process.env.CLIENT_SECRET,
grant_type: 'client_credentials'
}
};
request.post(options, (err, res, body) => {
if(err) {
return console.log(err)
}
console.log(`Status: ${res.statusCode}`)
console.log(body);
callback(res);
});
}
var AT = '';
var info = '';
getToken(process.env.GET_TOKEN, (res) => {
AT = res.body.access_token;
return AT;
});
const getGames = (url, accessToken, callback) => {
const gameOptions = {
url: process.env.GET_GAMES,
method: 'GET',
headers: {
'Client-ID': process.env.CLIENT_ID,
'Authorization': 'Bearer ' + accessToken
}
};
request.get(gameOptions, (err, res, body) => {
if(err) {
return console.log(err);
}
let x = '';
console.log(`Status: ${res.statusCode}`);
//console.log(JSON.parse(body));
info = JSON.parse(body);
console.log(info);
//res.send(parsed);
//req.body.getinfo = JSON.parse(body);
}).pipe(res);
}
setTimeout(() => {
getGames(process.env.GET_GAMES, AT, (response) => {
});
}, 1000);
//res.send(info);
});
app.listen(PORT, () => {
console.log(`Example app listening on port ${PORT}`);
});

How to get nodejs api data in reacj js in axiuos or fetch api

I have a question regarding zoom API.
How to fetch nodeJs API data in reacjJs in axiuos or fetch API,
I am trying to fetch data from nodeJs in reactJs, but I am getting a null response.
My code is below.
Node.js:
router.get('/auth', function(req, res, next) {
if (req.query.code) {
let url = 'https://zoom.us/oauth/token?grant_type=authorization_code&code=' + req.query.code + '&redirect_uri=' + process.env.redirectURL;
request.post(url, (error, response, body) => {
// Parse response to JSON
body = JSON.parse(body);
console.log(`access_token: ${body.access_token}`);
console.log(`refresh_token: ${body.refresh_token}`);
if (body.access_token) {
request.get('https://api.zoom.us/v2/users/me', (error, response, body) => {
if (error) {
console.log('API Response Error: ', error)
} else {
body = JSON.parse(body);
console.log('API call ', body);
var JSONResponse = '<pre><code>' + JSON.stringify(body, null, 2) + '</code></pre>'
res.send(`
<style>
</style>
<h2>${body.first_name} ${body.last_name}</h2>
<p>${body.role_name}, ${body.company}</p>
${JSONResponse}
`);
}
}).auth(null, null, true, body.access_token);
} else {
// Handle errors, something's gone wrong!
}
}).auth(process.env.clientID, process.env.clientSecret);
return;
}
React.js:
componentDidMount() {
const url = 'http://localhost:3000/api';
axios.post(
url,
{
path: '/v2/users/info#data.nyc',
methode: 'GET'
}
)
.then((response) => {
console.log(response)
},
(error) => {
console.log(error)
}
);
}
Your axios call is incorrect. Try below.
componentDidMount() {
const url = 'http://localhost:3000/api';
axios
.get(url + '/v2/users/info#data.nyc')
.then(function (response) {
// handle success
console.log(response);
})
.catch(function (error) {
// handle error
console.log(error);
});
}
i suggest u to fix the axios page:
try this:
const url = 'http://localhost:3000/api';
const zoom = () => {
Axios.get(url + '/v2/users/info#data.nyc')
.then((response) => {
console.log(response)
})
};

Make a synchroneous request in NodeJS

I am trying to make a post request using NodeJS and request.
I tried using promises and the async/await like other post says but I can manage to make work.
const express = require('express');
const bodyParser = require('body-parser');
var request = require("request");
const app = express();
app.use(bodyParser.json());
var token = '';
process.env["NODE_TLS_REJECT_UNAUTHORIZED"] = 0;
function postRequest(options) {
request(options, function (error, response, body) {
if (error) throw new Error(error);
token = (JSON.parse(body)).access_token;
console.log(token + 'tet');
return (token);
});
}
async function requestToken() {
var options = {
method: 'POST',
url: 'https://simplivity#xxxx/api/oauth/token',
headers: { 'Content-Type': 'application/json' },
formData:
{
grant_type: 'password',
username: 'administrator#vsphere.local',
password: 'xxxx'
}
};
try {
var test = await postRequest(options)
return (test);
} catch (error) {
console.error(error);
}
}
var test = requestToken();
console.log(test + 'TOT');
This is the answer :
[object Promise]TOT
00bd0beb-8967-4534-8c63-2e5d0d6876d4tet
Which should be the opposite.
thank you for your help.
(async () => {
var test = await requestToken();
console.log(test + 'TOT');
})();
While not very tidy something like this should work.
Better:
requestToken()
.then(response => {
console.log(response);
});
You need to return a promise.
Change your postRequest to:
function postRequest(options) {
return new Promise(function(resolve, reject) {
request(options, function (error, response, body) {
if (error) throw new Error(error);
token = (JSON.parse(body)).access_token;
console.log(token + 'tet');
resolve(token);
});
});
}

Axios POSTed FormData has empty body on serverside

This is the client side code. Data is not empty, file is getting uploaded correctly.
export function addGame(data) {
return dispatch => {
const formData = new FormData();
formData.append("game.cover", data.gameCover[0]);
formData.append("game.title", data.gameTitle);
formData.append("game.price", data.gamePrice);
formData.append("game.description", data.description);
return axios.post(apiUrl + "/games/add", formData).then(res => {
dispatch({ type: ADD_GAME, payload: res.data.game });
});
};
}
and this is the serverside
router.post("/add", auth, async (req, res) => {
const body = await req.body;
console.log(body);
let formErrors = [];
if (!body.gameTitle) formErrors.push("Game title is required.");
if (!body.description) formErrors.push("Description is required.");
if (!body.gamePrice) formErrors.push("Price is required.");
if (formErrors.length) res.status(400).send({ success: false, formErrors });
else {
let gameCoverFileName;
if (!fileUpload(req, gameCoverFileName))
formErrors.push("Failed to upload file");
const result = await gameModel.create({
title: body.gameTitle,
cover: gameCoverFileName,
price: body.gamePrice,
description: body.description
});
if (result)
res.status(201).send({
success: true,
game: {
gameTitle: result.title,
gameCover: gameCoverFileName,
gamePrice: result.price,
description: result.description
}
});
} });
And I'm getting empty body
You need to additionally process the multipart form-data. For example with multiparty:
const multiparty = require("multiparty");
router.post("/add", auth, async (req, res) => {
try {
const parse = function (req) {
return new Promise(function(resolve, reject) {
const form = new multiparty.Form()
form.parse(req, function(err, fields, files) {
!err ? resolve([fields, files]) : reject(err)
})
})
}
const [body] = await parse(req)
console.log(body)
} catch (err) {
console.log(err)
}
res.json("ok")
})

Mongoose remove and create in get route

I have a small issue with mongoose, what I am doing is getting data from online rss feeds, parsing it, and passing it to an array, from which I feed a mongoose model, and all this happens in the get route, what I want to accomplish is delete all the data first from the mongoose model and then populate it with the new data, but it always either deletes the data all together, since the parser iterates a few times, or it doesn't delete anything and the data just keeps adding to the model.
Here's my code
'use strict';
const Promise = require('bluebird');
const request = require('request');
const FeedParser = require('feedparser');
const express = require('express');
const router = express.Router();
const xray = require('x-ray')();
var Post = require('../models/post');
var dataArray = [];
router.get('/', function (req, res) {
const fetch = (url) => {
return new Promise((resolve, reject) => {
if (!url) {
return reject(new Error(`Bad URL (url: ${url}`));
}
const feedparser = new FeedParser();
const items = [];
feedparser.on('error', (e) => {
return reject(e);
}).on('readable', () => {
// This is where the action is!
var item;
console.time('loading')
while (item = feedparser.read()) {
items.push(item);
}
}).on('end', () => {
resolve({
meta: feedparser.meta,
records: items
});
});
request({
method: 'GET',
url: url
}, (e, res, body) => {
if (e) {
return reject(e);
} else if (res.statusCode != 200) {
return reject(new Error(`Bad status code (status: ${res.statusCode}, url: ${url})`));
}
feedparser.end(body);
feedparser.on('end', function () {
console.log('Done');
});
});
});
};
Promise.map([
'url',
'url',
'url',
'url'], (url) => fetch(url), { concurrency: 4 }) // note that concurrency limit
.then((feeds) => {
feeds.forEach(feed => {
feed.records.forEach(record => {
dataArray.push(record);
});
});
}).catch(function (error) {
console.log(error);
});
Post.remove({}, function (err) {
if (err) {
console.log(err);
} else {
console.log('collection removed');
}
});
dataArray.forEach(post => {
Post.create({
title: post.title,
content: post.description,
created: post.date,
image: post['rss:image']['#'],
link: post.link
}, function (err, newPost) {
console.log(newPost.title);
});
});
Post.find({}, function (err, posts) {
if (err) {
console.log(err);
} else {
res.render('index/home', {
posts: posts
});
}
});
});
module.exports = router;
None of this is going to run synchronously. You can do Something like this :
'use strict';
const Promise = require('bluebird');
const request = require('request');
const FeedParser = require('feedparser');
const express = require('express');
const router = express.Router();
const xray = require('x-ray')();
var Post = require('../models/post');
var dataArray = [];
const fetch;
router.get('/', function (req, res) {
Post.remove({}, function (err) {
if (err) {
console.log(err);
} else {
console.log('collection removed. Starting to fetch Posts from Service');
fetch = (url) => {
return new Promise((resolve, reject) => {
if (!url) {
return reject(new Error(`Bad URL (url: ${url}`));
}
const feedparser = new FeedParser();
const items = [];
feedparser.on('error', (e) => {
return reject(e);
}).on('readable', () => {
// This is where the action is!
var item;
console.time('loading')
while (item = feedparser.read()) {
items.push(item);
}
}).on('end', () => {
resolve({
meta: feedparser.meta,
records: items
});
});
request({
method: 'GET',
url: url
}, (e, res, body) => {
if (e) {
return reject(e);
} else if (res.statusCode != 200) {
return reject(new Error(`Bad status code (status: ${res.statusCode}, url: ${url})`));
}
feedparser.end(body);
feedparser.on('end', function () {
console.log('Done');
});
});
});
};
}
});
Promise.map([
'url',
'url',
'url',
'url'], (url) => fetch(url), { concurrency: 4 }) // note that concurrency limit
.then((feeds) => {
feeds.forEach(feed => {
dataArray = dataArray.concat(feed.records);
/*feed.records.forEach(record => {
dataArray.push(record);
});*/
});
console.log('inserting posts in the collection');
dataArray.forEach(post => {
Post.create({
title: post.title,
content: post.description,
created: post.date,
image: post['rss:image']['#'],
link: post.link
}, function (err, newPost) {
console.log(newPost.title);
});
});
console.log("Fetching posts from the collection");
Post.find({}, function (err, posts) {
if (err) {
console.log(err);
} else {
res.render('index/home', {
posts: posts
});
}
});
}).catch(function (error) {
console.log(error);
});
});
module.exports = router;
I haven't tested this. Please test it on your end. Let me know if there's an error or something.

Resources