Exporting module in node.js - javascript

I have the following my custom module that successfully exports.
module.exports = function(callback) {
var request = require("request")
var url = "http://sheetsu.com/apis/94dc0db4"
request({
url: url,
json: true
}, function (error, response, body) {
if (!error && response.statusCode === 200) {
callback(body)
}
})
Now if I try to change the way to export this as the following, I get 404 error.
var data = function(callback) {
var request = require("request")
var url = "http://sheetsu.com/apis/94dc0db4"
request({
url: url,
json: true
}, function (error, response, body) {
if (!error && response.statusCode === 200) {
callback(body)
}
})
}
module.exports = data;
What am I doing wrong?
UPDATE
This is the route index.js that renders the received data.
var data = require('../lib/data.js');
data(function(data) {
router.get('/', function(req, res, next) {
res.render('index', {
title: 'Express',
data: data
});
});
});
And the error is at at /Users/xxxxx/Dev/Project/app.js:32:13
I haven't changed any other codes except how I changed the export part.

You should call your function inside the route, not vice a verca:
router.get('/', function(req, res, next) {
data(function(d) {
res.render('index', {
title: 'Express',
data: data
});
});
});

Related

Refresh access token express js

I have an express server that gets a list of podcasts, from an endpoint.
This apart works fine, but there is a token that I use in requests to authorize entry to the endpoints.
the response when gaining an access token looks like:
{ access_token: '8c9d31761cbd32da25f1f1b988b527cde01c9d8a',
expires_in: 604800,
token_type: 'Bearer',
scope: 'podcast_read episode_read podcast_update episode_publish' }
I have a refresh token that I use when refreshing the token and works well.
The way I'm doing it at the moment is, I have a text file that holds the token, the app reads from this when making a request, I have set up a function, that is called every time the podcasts route is called router.get('/podcasts', checkIfTokenValid, (req, res, next) => { to check if the token is valid or expired if so, refresh the token and write the new token to the file.
The only thing about this is; the write to file function is executed after the podcasts route connects to the endpoint, so the old access token is used.
Logging to the console, the functions are executed before the podcasts route gets all the podcasts, except for the writeAccessTokenToFile() function.
Just wondering, is there a better way to do this?
var express = require('express');
var router = express.Router();
var app = express();
var path = require('path');
var fs = require('fs');
const request = require('request');
var refreshToken = '425153ed4ddb4aee5sjsjsfaeffc46ab9944aece0400f';
var clientId = 'myId';
var client_secret = 'secret';
var isAccessTokenValid;
var access_token_file = path.join(__dirname, 'access_token.txt');
function refreshAccessToken() {
console.log('refreshAccessToken')
var body = { 'grant_type': 'refresh_token', 'refresh_token': refreshToken }
var options = {
url: `https://api.podbean.com/v1/oauth/token`,
headers: { 'Authorization': 'Basic ' + new Buffer(clientId + ":" + client_secret).toString('base64') },
json: body
}
request.post(options, (err, response, body) => {
// console.log(body.expires_in*1000)
if (err) {
return response.status(500).json({
title: 'An error has occured',
error: err
})
}
console.log(body)
writeAccessTokenToFile(body.access_token);
})
}
function getAccessToken() {
return fs.readFileSync(access_token_file, 'utf8');
}
function writeAccessTokenToFile(token) {
console.log('writeAccessTokenToFile = '+ token)
var data = getAccessToken();
var result = data.replace(data, token);
fs.writeFileSync(access_token_file, result, 'utf8');
}
function checkIfTokenValid (req, res, next) {
console.log('checkIfTokenValid')
var options = {
url: `https://api.podbean.com/v1/oauth/debugToken?access_token=${getAccessToken()}`,
headers: { 'Authorization': 'Basic ' + new Buffer(clientId + ":" + client_secret).toString('base64') }
}
request(options, (err, response, body) => {
if (err) {
return res.status(500).json({
title: 'An error has occured',
error: err
})
}
// console.log(JSON.parse(body))
isAccessTokenValid = JSON.parse(body).is_valid;
if (isAccessTokenValid) {
refreshAccessToken();
}
next();
})
};
router.get('/podcasts', checkIfTokenValid, (req, res, next) => {
var options = {
url: `https://api.podbean.com/v1/podcasts?access_token=${getAccessToken()}`
}
request(options, (err, response, body) => {
if (err) {
return res.status(500).json({
title: 'An error has occured',
error: err
})
}
res.json(JSON.parse(body));
next();
})
});
module.exports = router;

How to add Get or POST request in the following code

How to add Get or POST request in the following code. My code is running fine. However, how can i add request like GET, POST, PUT OR DELETE
var expect = require('chai').expect;
var request = require('request');
describe('Status and content', function() {
describe ('Main page', function() {
it('status', function(done){
request('http://localhost:3000/', function(error, response, body) {
expect(response.statusCode).to.equal(200);
done();
});
});
it('content', function(done) {
request('http://localhost:3000/' , function(error, response, body) {
//expect(body).to.equal('Hello World');
done();
});
});
});
describe ('About page', function() {
it('status', function(done){
request('http://localhost:3000/', function(error, response, body) {
expect(response.statusCode).to.equal(200);
done();
});
});
});
});
Also, before running this code how i can install and run the JSON server so the api is ready on the localhost. So i do not have to manually do it.
https://medium.com/codingthesmartway-com-blog/create-a-rest-api-with-json-server-36da8680136d?fbclid=IwAR2mEtB6-BKAsSgUto3aOTjx8WmAbsfKB6RkSvHeZbI4Jt0fiqMwbV_QvGw
You can use request module in this way.
let options = {};
options.method = 'GET';
options.uri = 'http://localhost:3000/';
request(options, function(err, res, body){
//....
});
Also for 'POST',
let options = {};
options.method = 'POST';
options.uri = 'http://localhost:3000/';
options.body = {payload};
options.headers = {}; //headers if any
request(options, function(err, res, body) {
//.....
});

react / expressjs / multer don't save image

i send a file from "react dropzone component" to "node server" and try to upload this with "multer" but no show any error, the file no upload and req.file/s is undefined
var express = require('express');
var router = express.Router();
var msg = require('../helpers/MessageHandler');
var CM = require('../helpers/ContentMessages.json');
var storage = multer.diskStorage({
destination: function(req, file, cb) {
cb(null, 'public/uploads/');
},
filename: function(req, file, cb) {
cb(null, Date.now() + file.originalname);
}
});
var upload = multer({storage: storage}).any();
var path = '/enterprise';
router.post(path, function(req, res, next) {
var enterprise = req.body.obj;
console.log(req.body);
console.log(req.files);
console.log(req.file);
upload(req, res, function(err) {
if(err) {
return res.status(500).json(msg.prototype.errorMsg(err));
} else {
return res.status(200).json(msg.prototype.success(CM.message.success.doc_create, null));
}
});
});
the react component is somthing like this,
in the fetch function i send a object with all the fields
insertObj (values) {
console.info(values);
const obj = JSON.stringify({obj: values});
let url = '/api/v1/enterprise';
const headers = { 'Content-Type': 'application/json', 'Access-Control-Request-Method': '*'};
const req = new Request(url, {method: 'POST', headers: headers, body: obj});
fetch(req)
.then((response) => {
return response.json();
})
.then((enterprise) => {
console.log(enterprise);
}).catch((error) => {
console.log(error);
});
}
inside multer req.files will be visible. So change your code to this:
upload(req, res, function(err) {
var enterprise = req.body.obj;
console.log(req.body);
console.log(req.files);
console.log(req.file);
if(err) {
return res.status(500).json(msg.prototype.errorMsg(err));
} else {
return res.status(200).json(msg.prototype.success(CM.message.success.doc_create, null));
}
});
Also instead of 'Content-Type': 'application/json' there should be enctype='multipart/form-data'.

ExpressJS to ejs, getting HTTP 500 error

I have the following code, but I'm getting HTTP 500 error and the page is being re-directed to error.ejs.
However, the console.log(body) works fine. The problem is being seen in res.render. I'm unable to see any error in console (Tried by setting the env=development too)
var express = require('express');
var router = express.Router();
var request = require('request');
/* GET home page. */
router.get('/', function(req, res, next) {
// Set the headers
var headers = {
'Subscription-Key': 'XXXXXXXX',
'Content-Type': 'application/x-www-form-urlencoded'
}
// Configure the request
var options = {
url: 'http://External_Web_Service_REST_URL',
method: 'GET',
headers: headers
}
var result;
// Start the request
request(options, function(error, response, body) {
if (!error && response.statusCode == 200) {
// Print out the response body
result = body;
console.log(result); //This works
}
})
res.render('in', {
title: JSON.parse(result)
}); //Problem seen here, No logs printed
});
module.exports = router;
The problem here is that res.render is executed before request call completes.
Remember request is async. The fix is to move res.render inside request callback
....
router.get('/', function(req, res, next) {
...
request(options, function(error, response, body) {
if (!error && response.statusCode == 200) {
// Print out the response body
result = body;
console.log(result); //This works
//respond from here
res.render('in', {
.parse(result)
});
} else {
res.render('error');
}
})
})
module.exports = router;

Node.js & Express.js/Jade res.render returns res.render is not a function

I haven't been able to find an answer to this error as of yet and am wondering if it has to do with version 4 of Express
controller.js
var request = require('request');
var apiOptions = {
server : "http://localhost:3000"
};
if(process.env.NODE_ENV === 'production') {
apiOptions.server = "https://heroku_path";
}
module.exports.homelist = function(req, res) {
var requestOptions, path;
path = '/api/locations';
requestOptions = {
url: apiOptions.server + path,
method: "GET",
json: {},
qs : {
lng : -117.929835,
lat : 33.614675,
max : 30000
}
};
request(requestOptions, function(err, res, body) {
renderHomepage(req, res, body);
});
var renderHomepage = function(req, res, body) {
res.render('jade-template', {
title: 'I'm a main title',
pageHeader: {
title: 'I'm a title',
strapline: 'I'm a strapline'
},
locations: body,
sidebar: 'yadda yadda'
});
};
The homelist function gets called from my routes.js which is then where my API gets called from my request with the query found in requestOptions.
however when the request callback is fired and renderHomepage in invoked with the API variable body I get the error:
res.render('jade-template', {
^
TypeError: res.render is not a function
All my routes are set up and tested fine. Does anyone have a solution for this?
The res argument in the renderHomepage function (the request's callback) is not the same as the res of the express route!
Change your call the request to something like:
request(requestOptions, function(err, serverRes, body) {
renderHomepage(req, res, body);
});
Then the response to your request to /api/locations is serverRes, and the response you send to your client is res.

Categories