I should preface my post by saying that I am a beginner and this is my first time using Node.js and Express in a real project.
I have a simple Node.js/Express project and I want to read a JSON object from a URL. Afterwards, I intend to build another url that displays html from an external website using iframe.
I read about the 'request' module online and know that I need to do something along these lines:
var express = require('express');
var router = express.Router();
var request = require('request');
// Urls for App Center REST functions
var url = 'https://someserver.com/appserver/portal/api/1.0/results/recent';
/* GET list of recent reports */
router.get('/testapi', function(req, res, next) {
res.render('testapi', { title: 'List Recent Reports' });
});
/* TEST: function to GET report list */
router.get('/recentreports', function(req, res){
request({
url: url,
json: true
}, function (error, response, body) {
if (!error && response.statusCode === 200) {
console.log(body) // Print the json response
}
})
});
I have tried to define a function /recentreports which is called in the testapi.jade view, however nothing is printed in the console when I load the page and I suspect I am doing something horribly wrong.
My questions are:
How do I read the JSON into my app and where does this code go (index.js, app.js, testview.jade etc...?)
How do I export the URL I construct from wherever that code lives to my .jade view?
There was nothing logged to the browser console because no response was sent from your server. The response was only logged to the server's console.
You'll need to refactor the code for the 'recentreports' route to send data. You could use a simple res.send call:
...
function (error, response, body) {
if (!error && response.statusCode === 200) {
res.send(body) // Send the response to the client
}
}
...
This response will be received by testapi.jade via an AJAX call to the '/recentreports' route. The AJAX call can be defined in a Javascript file sourced by the testapi.jade file.
The constructed URL would not need to be exported as it exists within the same testapi.jade file (after you've formed it from the results from the AJAX call).
Related
I have created a get web api that i want to hit at my server startup for some specific task. I have used this method
var request = require('request');
request('http://localhost:3000/api/jobs/asd', function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log(body) // Print the google web page.
}
}
)
But i am getting status code as 403. So i am not able to access my API at serve startup. Please suggest me the proper solution for the same.
thanks in adv.
You can place your code inside http callback like so :
http.createServer(app).listen(3000, () => {
//your code here
});
Sorry, I tend to be a bad writer when I have not fully woken up, let me revise.
I am using expressjs with passportjs (local strategy) to manage my server and using connect-busboy to manage file uploading. I do not think passport will play a role in this.
Here is the server code for managing file uploads:
app.post('/upload', isLoggedIn, (req, res) => {
if(req.busboy){
req.pipe(req.busboy);
req.busboy.on('file', (fieldname, file, filename, encoding, mimetype) => {
if(mimetype.match(/^image\//)){
var root = path.join(__dirname, "../public/images/");
if(fs.existsSync(path.join(root, filename))){
var name = getUnique(path.join(root, filename));
} else {
var name = filename;
}
var ws = fs.createWriteStream(path.join(root, name), { flags: "a" });
file.pipe(ws);
}
});
}
});
As for my client page, it is used to change a JSON object which will get re-uploaded to the server as a configuration tool. When I upload a new image asynchronously I need to get the filename to update this JSON object while working on it. For uploading from the clients end I am using dropzonejs, which did not require any configuration on my part to work.
So, in summary I upload a number of images via dropzone asynchronously, busboy and fs on my server save the file, and I would like to get the filename returned to my javascript to modify the existing JSON object.
Edit solution:
Thanks to Elliot Blackburn for pointing me in the right direction.
By calling:
ws.on('close', () => {
res.send({filename: name});
});
after file.pipe(ws); to send the response back to the client. On the client side modify dropzone to handle the response like so:
dropzone.on('success', (file, res) => {
console.log(res);
});
Just send it in the normal http response. It'll depend what library you're using but most will allow you to trigger a normal req, res, next express call. From that you can access the file object, and return anything you want.
Something like:
req.send({filename: name}); // name is the filename var set earlier in the code.
Once you've finished editing the file and such, you can get the name and put it into that returned object and your client will receive that as object as the response which you can act upon.
I'm new to node.js so I'll try my best to explain the problem here. Let me know if any clerification is needed.
In my node.js application I'm trying to take a code (which was received from the response of the 1st call to an API), and use that a code to make a 2nd request(GET request) to another API service. The callback url of the 1st call is /pass. However I got an empty response from the service for this 2nd call.
My understanding is that after the call back from the 1st call, the function in app.get('/pass', function (req, res).. gets invoked and it sends a GET request. What am I doing wrong here? Many thanks in advance!
Here is the part where I try to make a GET request from node.js server and receive an empty response:
app.get('/pass', function (req, res){
var options = {
url: 'https://the url that I make GET request to',
method: 'GET',
headers: {
'authorization_code': code,
'Customer-Id':'someID',
'Customer-Secret':'somePassword'
}
};
request(options, function(err, res, body) {
console.log(res);
});
});
Im a little confused by what you are asking so ill just try to cover what i think you're looking for.
app.get('/pass', (req, res) => {
res.send("hello!"); // localhost:port/pass will return hello
})
Now, if you are trying to call a get request from the request library when the /pass endpoint is called things are still similar. First, i think you can remove the 'method' : 'GET' keys and values as they are not necessary. Now the code will be mostly the same as before except for the response.
app.get('/pass', (req, res) => {
var options = {
url: 'https://the url that I make GET request to',
headers: {
'authorization_code': code,
'Customer-Id':'someID',
'Customer-Secret':'somePassword'
}
};
request(options, function(err, res, body) {
// may need to JSONparse the body before sending depending on what is to be expected.
res.send(body); // this sends the data back
});
});
I have a request that needs to be made upon app initialization in which part of the JSON response is parsed into JS and has to be written to a file – the rest of the response also needs to be received by the front end. Currently I have it setup like this:
function getAds(req, res) {
console.log('GET Advertisements');
let url = 'http://example.com/json/advertisements/v5/all';
request(url, (err, response, body) => {
let advertisements = JSON.parse(body);
let script = advertisements.header;
fs.writeFile('client/ads/dfpAds.js', script, function(err) {
if (err) {
console.error(err);
}
});
res.send(advertisements);
});
}
This successfully writes to the JavaScript file, but it does not send the response to my front end and also blocks all other HTTP requests I'm making in other controllers.
Is it possible to do this? Do I need to separate the request that will handle the WriteFile and the other that will be sent to the front end?
I've tried a variety of combinations but I can never get the WriteFile to not block all other HTTP requests regardless. Any help is very much appreciated.
I have this system
An API system which only response with JSON objects.
Example: http://example.com/user/13
response: {name:'Aesome 1', age: '13'}
ExpressJS web app which creates the views and sends the views to the user.
Now what I need to do it to get the JSON object from the API and render a view in ExpressJS and then send to the client.
So I need to connect the ExpressJS app with this api system.
Please let me know how to do this.
Thanks
You can use the request module for making api requests.
In your controller, do like this:
var request = require('request');
function(req, res) {
request.get('http://example.com/user/13', function(err, response, body) {
if (!err && response.statusCode == 200) {
var locals = JSON.parse(body);
res.render('<YOUR TEMPLATE>', locals);
}
}
}
Note: If you really want to access api from server then use the sample, else you can fetch the result using ajax with less overhead of another server to server http call.