I am connecting to an api and pulling a set of json data. the javascript outputs the json as the variable feedData and when i include that in a html i get the json on a html page as expected. What i want to do is output it as a json endpoint. I tried to get fancy and when i tried:
var express = require('express');
var app = express();
app.get('/', function (req, res) {
res.send(feedData);
});
app.listen(3000, function () {
console.log('posting data');
});
the problem is that i need to import an api.js file and when i attempt to load this i get an error related to the api.js file which is windows is not defined. Like i said, the html
document.getElementById('mydiv').innerHTML += JSON.stringify(feedData, undefined,2);
then
<pre id="mydiv"></pre>
works fine but i will also to recall every x seconds because this is a live json feed.
Currently, i just decided to connect via python, loading it into mongodb and creating a nodejs endpoint from there, which works fine, but it seems there should be a way here.
Try using res.json, res.json(feedData); to send objects. If you want to send a string just, use res.send
Instead of
res.send(feedData);
use
res.json(feedData);
Hope this helps
Related
I'm facing an issue when I want to pass some data through http.post from my angular client to my node.js server.
Here is the thing, passing text with JSON.stringify(my text) works fine, but given that I want to pass a file + my text, I would like to use formData.
When I try to get back the data in the server side, my req.body is empty, and i'm not able to retrieve the data.
Here is my client side code :
[...]
var formData = new FormData();
formData.append('name', product.name);
formData.append('benefits_detail', product.benefits_detail);
formData.append('sections', product.sections);
formData.append('image', product.image); // image is my file
return this.http.post('http://localhost:3000/product', formData, {headers: headers}).map(........)
Then my server, where I try to get back my data :
router.post('/', function (req, res, next) {
console.log('req.body');
console.log(req.body);
console.log(req.body.formData);
...
Here the console.log are empty like showing : {}
Anybody can help with this ?
Thanks you
It looks like you're not using any body parsing middleware, which is required.
From the Express documentation for req.body
Contains key-value pairs of data submitted in the request body. By default, it is undefined, and is populated when you use body-parsing middleware such as body-parser and multer.
Try using body-parser
For uploading images to a server, you could try to use the Ng File Upload directive. It has a directive to select the file in HTML and then to Upload the file to the server. If you are already selecting the image, I believe you can just use the Uploading part in JS to send the image (have never tried using the Upload without the file selector in HTML, but It should work).
However, this solution would require you to send two requests though, one for the data and another for the image.
Trying to do something seemingly basic.
I'd like to create a POST request through which I'll be sending JSONs. These JSONs will be created into files, which I'd like to return to the user via download.
The use case for this is that I'm building an application which takes a form and converts it into a JSON for upload to a MongoDB database. Users can load these JSONs into the application to re-load their old records as templates.
This is how I'm approaching it as of now:
// Download JSON Previews
var jsondownload = {};
// Grabs the JSON from POST request
app.post('/api/download', function(req, res, next){
jsondownload = {};
var json = req.body;
jsondownload = json;
res.json(jsondownload);
next();
});
// Immediately downloads the JSON thereafter
app.get('/api/download', function(req, res){
res.set({"Content-Disposition":"attachment; filename='test.json'"});
res.send(jsondownload);
});
What's the right way to do this?
There is no one "right" way to do it, but a few solutions include:
Remove the GET route handler (and the jsondownload variable) completely and just respond immediately with the Content-Disposition set appropriately. This is the better of the 3 because it reduces code and keeps things simple.
Use a simple redirect in your POST route handler. Instead of responding with the JSON immediately, you would do res.redirect('/api/download').
Do more or less what currently doing, but move the logic (the res.set() and res.send()) to a separate function that gets called from both route handlers.
I'd like to be able to parse a url query for data and use it in my response. In my app file I have the following:
var entry = require('./routes/entry');
app.use('/entry*', entry);
in my route file:
router.get('/:name', function(req, res) {
res.send(req.params.name);
});
module.exports = router;
Currently I am getting a 404 error.
I'm wondering how I can get a name parameter out of the url. So if someone were to type .../entry/example then the response would be "example."
A lot of my confusion stems from what should be handled by the router and what the app.use should have as its URL parameter. Thanks so much!
Remove the asterisk * from /entry and it should start working as expected. I created a local express application and inserting the asterisk causes the same issue.
Inexperienced with nodejs style programming, I'm looking at an open-source node.js app that has routes with the same paths in both the front-end main.js file and the routes.js file, as you see below. I'm assuming that when the function in main.js file gets called it triggers the route in routes.js, however, I can't figure out what if anything is getting passed from main.js to routes.js as a callback.
main.js
$.get('/ip', function (data) {
fp.val(fingerprint);
userId.val(md5(fingerprint + data.ip));
});
routes.js
app.get('/ip', function (req, res) {
res.json({
ip: req.connection.remoteAddress
});
});
There's nothing node-specific about the frontend script, it's just using jQuery.get to get the document at a given URL.
On the server-side, it looks like the app is using Express (or something like it) which modifies the .send() method of the response to allow sending arbitrary objects. When you send and object, Express JSON encodes it (using JSON.stringify(object) and sets the Content-Type header of the response to application/json. This content-type header is what tells jQuery to automatically parse the JSON response back into an object in the browser.
So there is no callback being passed from main.js to routes.js, it's just a bog-standard web request that sends JSON data back to the client.
How does one get the response of an express app as a string given a request object?
In other words, I want a way to send a request object to an express app and receive its response as a string.
As code, I am looking for some implementation of the sendToThisApp method:
var app = express();
app.get( /* Some code here */ );
var request = // Some request object
var response = app.sendToThisApp(req)
console.log(response);
Thanks.
Here is the code for a simple Node.js Express app :
var app, express;
express = require('express');
app = express();
app.get('/', function(req, res) {
console.log(res);
res.end();
});
app.listen(8080);
In order to trigger a get request on this app, you need to run the app on node. Open a terminal and type this command:
node app.js
Then, you only need to start your favorite browser, go to localhost:8080, and look back at the log of the response in your terminal.
It looks like you're expecting things to happen synchronously that node and express want to handle asynchronously through callbacks.
But aside from that, I'm not really understanding what you're trying to do.
If you have the code for the node app, and you just want to see the response object as a string, then the easiest way to handle that is through the callback on the get.
app.get('/', function(req,res){
console.log(res);
}
But without knowing what you're actually after, I can't give better advice.