So I am trying to retrieve images from my expressjs API and I cannot seem to actually retrieve anything, not locally or even remotely.
Here is the written code below :)
app.use(express.static(path.join(__dirname,'/public/')));
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.get('/getImage/:folder/:imageName', function (req, res) {
console.log(path.join(__dirname,'/',req.params.folder,'/',req.params.imageName));
res.sendFile(path.join(__dirname,'/',req.params.folder,'/',req.params.imageName));
res.end();
});
Have I written something wrong? Is there something I am missing?
here is the request http://localhost:3000/getImage/public/da4b9237bacccdf19c0760cab7aec4a8359010b0678f63452c5c1d428cd376dd82c55aa33a34e600.jpg
UPDATE
So it works when I remove res.end(), I'm assuming this is being executed before the image has fully been received?
Related
I am having trouble with a node.js/express application I am trying to run.
When running on localhost, the data I pass to the route is parsed and I am able to use req.body.message successfully. However on my live site, this only returns undefined. Why is this, and how do I fix it?
This is the node.js app I am using on both the localhost and the live server.
const express = require("express");
const cors = require("cors");
const router = express.Router();
const app = express();
router.post("/send", (req, res) => {
res.send(`message is ${req.body.message}`);
});
app.use(cors());
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use("/", router);
const PORT = 3030;
app.listen(PORT, () => console.log("Server on " + PORT));
If I do a POST with "message":"hello", on my localhost, I get the response with the "message is hello", but on the live server I get "message is undefined".
Any advice appreciated, cheers.
app.use(cors());
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
Try putting all this middleware before '/send' API end point. Also check console errors that will give you more information about error.
I solved it. When calling the live api, you need to include a trailing slash.
E.g. examplewebsite.com/send will not work. However, examplewebsite.com/send/ will work.
I don't know enough about how servers work to explain this, but it solved my problem. I hope anyone else with this issue can benefit from my finding.
coding image
output image
it showing a extra space when i do post method using REST API method
You are not parsing your data correctly. You need to POST the object as JSON.stringify(yourobject) and then have nodejs run jsonencoder to parse the data correctly, otherwise your request body will always be null. Below is an example.
var jsonencodedParser = bodyParser.json({ extended: false });
app.post('/test', jsonencodedParser, function (req, res) {
console.log('this is req.body');
console.log(req.body);
res.status(205)
res.send();
})//end function
I'm trying to test using NodeJS as a backend api for a Polymer front end. On the Polymer side, I have this iron-ajax element:
<iron-ajax
id='test-req'
url='http://localhost:9090/backend-test'
handle-as='text'
on-response='testRsp'
body='{"data":"stuff"}'>
</iron-ajax>
The testRsp handler simply logs the response text to the console. On the backend, this is my route:
app.get('/backend-test', function(req, res){
res.send(req.body)
console.log(req.body)
}
As you can see, all it does is respond with the raw request, and log the request on the backend. Both sides as expected have the same result, but unfortunately the result is just {}.
Now, I also tried sending the json in via the params attribute instead of the body attribute of the iron-ajax element, and on the backend I used the deprecated req.param() function like so: req.param('data'), and that correctly prints out stuff on both the browser and the backend. However, since it is deprecated, I'm trying to avoid that method.
Any suggestions?
Edit: I figured this extra piece of info would be helpful. When I log req.originalUrl on the backend when passing the json in 'params', I get /backend-test?data=stuff. When passing in 'body', it's just /backend-test.
I also want to note that I have tried variations of the bodyParser middleware as well:
->app.use(bodyParser.json()) (outcome as noted above)
->app.use(bodyParser.text()) (same)
->not using bodyParser at all (prints undefined as expected based on the express docs)
->app.use(bodyParser.text()); app.use(bodyParser.urlencoded({ extended: true })); (same output as json() and text(); taken from the req.body docs).
Edit2 Thanks AP. I have been putting the use statements before any route definitions, like so:
// Create Express object, enable CORS
var app = express()
app.use(bodyParser.json())
app.use(cors())
// Route definitions
app.post('/backend_test', function(req, res){
res.json(req.body)
console.log(req.body)
})
app.listen(9090, function() {
console.log('App started, listening on port 9090')
})
I also updated my iron-ajax element to explicitly make a post rather than get, and set content type as json, but no dice. I'm still getting only {} out the other side:
<iron-ajax
id='test-req'
url='http://localhost:9090/backend_test'
content-type="json"
method="post"
handle-as='json'
on-response='testRsp'
body='{"data":"stuff"}'>
</iron-ajax>
Edit3 I found the mistake with my update, content-type needed to be application/json, not just json. That got it working finally. Thanks!
Your middleware should be initialized before your routes, and should somewhat resemble this:
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
In terms of the Polymer Implementation, if you are sending JSON data, according to the docs your element should also contain:
<iron-ajax content-type='json'>
There is also a demo-repository that show's an example MEAN stack server running polymer as it's front-end. Which I believe ties into your question as well?
PS. Youtube-Black is a more comprehensive example.
Edit:
I just realized you're missing the method attribute on your Polymer element. Without that, you are sending a GET request! Make sure to use your element like so, in addition to your other props:
<iron-ajax content-type='json' method='post'>
Client side, this is what I have happening:
function saveGrades() {
$.post("/savegrades", {classIndex: "classIndexId"}); }
Server side:
router.post('/savegrades', stormpath.loginRequired, function(req, res) {
console.log("Class index: " + req.body.classIndex);
console.log(req.body);
res.send(200);
});
My bodyParser settings are as follows:
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
No matter what I have tried, req.body is empty and does not have the classIndex. What am I doing incorrectly? Why is the data not being posted to the server?
Edit: For the linked questions, I have gone through almost all relevant answers here and am unable to find a solution. It seems that that data is never being sent to the server whatsoever. The body is always empty when I check it with a debugger.
Can you please check the code,
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
implemented well before,
router.post('/savegrades',
Based on your comment,
Can you please trying adding Trying adding mime type (content type) in client.
Try this and send data through POSTMEN to verify that data is actually comming then send it through function
var bodyParser = require('body-parser');
app.use(bodyParser.json()); // support json encoded bodies
app.use(bodyParser.urlencoded({ extended: true })); // support encoded bodies
app.post('/savegrades', function(req, res) {
console.log("Class index: " + req.body.classIndex);
console.log(req.body);
res.send(200);
});
I have the following code:
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: false }));
app.post('/rasp', function(req, res) {
res.send("received");
res.send(req.body.data);
});
app.listen(process.env.PORT || 5000);
I used POSTMAN to see if it worked and apparently the "received" text is sent back, but the data parameter is blank. What could be the problem?
Basically, the client sends a request and waits for a single response from your server. Once the client receives that response, it stops waiting for another. Furthermore, Express only allows you to send one response per request (going along with the client stuff explained above). You may be able to change this setting, but I've never dealt with it, so my answer will be limited to that knowledge.
Your server is executing res.send('received'); and the response is handled. You cannot call res.send again. You should be getting an error on your server when you attempt the second call.
You should send all data that the client needs in the first (and only) res.send().
Server responses should not be handled like logging (ex: sending 'received', 'analyzing', etc). Keep the logging separate. The client doesn't want to know all that extra info, it just wants the expected data response.
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: false }));
app.listen(process.env.PORT || 5000);
app.post('/rasp', function(req, res) {
res.send({received:true,data:req.body});
});
can you try this one and writing the response here
I believe your post body is "data=Some Value".
If you want to send multiple chunks of data, you should use res.write, and res.end. In your code change the following lines
res.send("received");
res.send(req.body.data);
to
res.write("received");
res.end(req.body.data);