I use a REST client to test my app (Insomnia and postman). My app literally does nothing:
const express = require('express');
const app = express();
const fileUpload = require('express-fileupload');
app.use(express.json())
app.use(fileUpload());
app.post('/', fileUpload(), function(req, res) {
console.log(req.files)
res.send('a')
});
const PORT = 9999;
app.listen(PORT, () => {
console.log(`Server listening on port ${PORT}...`);
});
Whenever I try to upload a file to this service req.files is undefined. I took this code from express docs page and from a few stackoverflow questions and it just doesn't work for me. Content-length is good (40k seems right)
Content-type is auto set by my REST client. Do I have to change this?
I tried simply printing whole request object and body is empty and files is not even present there
So for anyone wondering. fileupload requires form-data Content-type. Moreover, it also requires a file to have a "key" within this form-data. It's a shame documentation fails to mention this.
Just do one thing: remove file fileUpload() from post endpoint and check, find below code for your reference.
app.post('/', function(req, res) {
console.log(req.files)
res.send('a')
});
Related
In very new to express js. I just wrote a simple program to send JSON request through postman and get the response.
Why I can't get any response? it always says could not get any response. I go through several tutorials and could not figure out what exact missing here?. Here is my code.
const express = require('express');
const app = express();
app.use(express.json);
app.post('/', (req, res) => {
console.log(req.body);
res.send(req.body);
});
app.listen(3000, () =>{
console.log("Listen in port 30000");
});
I figure out what went wrong. Here
app.use(express.json);
Should be This,
app.use(express.json());
You have to parse your json data inorder to consume it.
check the following code.
install this package.
npm i body-parser
and use it with your express object as below
let bodyParser = require('body-parser')
app.use(bodyParser.json())
I am sending a JSON response from Node.js server to a Slack App.
This response is displayed in raw form, as JSON, instead of being formatted properly.
Minimum code that replicates the problem:
server.js:
const express = require('express');
const app = express();
// POST request processing
app.post('/', function(req, res){
var arr1 = [{"type":"section","text":{"type":"mrkdwn","text":"*Lorem Ipsum*"}},
{"type":"section","text":{"type":"mrkdwn","text":"_Lorem Ipsum_"}},
{"type":"section","text":{"type":"mrkdwn","text":"`Lorem Ipsum`"}}]
res.setHeader('Content-Type', 'application/json');
res.json(arr1);
});
// Listen to the AppEngine/Heroku - specified port, or 8080 otherwise
const PORT = process.env.PORT || 8080;
app.listen(PORT, () => {
console.log('Server listening on port ${PORT}...');
});
The JSON message should be rendered like visible here:
api.slack.com/tools/block-kit-builder
Instead, it is displayed like this:
I have also tried this and numerous other ways:
res.end(JSON.stringify(arr1));
I've found this proper-way-to-return-json-using-node-or-express on SO, and looked through Slack and Node.js documentation. I've advanced quite far in my app, but responses are still not rendered properly, so I figured I would ask here.
Any ideas?
please use a simple express response res.send(your JSON object);
I am trying to cache a file client side with NodeJs and Express.
Here an example of what I am trying to do :
const path = require('path');
const express = require('express')
const app = express()
app.get('/', (req:any, res:any)=> res.send('Hello World!') );
app.get('/file', (req:any, res:any)=> {
console.log('Request URL:', req.originalUrl);
res.set('Cache-Control', 'public, max-age=60');
res.sendFile(path.resolve(__dirname+'/../file.pdf'));
});
app.listen(3000, ()=>console.log('Example app listening on port 3000!') );
Then I browse the file twice and I expect to have only one log Request URL: /file. But with this code I got two. It seems that either my Cache-Control headers is ignored by the browser or it get mixed up with default Express behavior like ETag..
Any Idea ?
I'm not sure but first thing that I thought about was the file size.
Maybe it is too big?
what-is-chrome-default-cache-size-limit
I found my question was asked a year ago here app.post() not working with Express but the code written there is outdated (the way bodyparser was added doesn't work anymore as well as function mentioned below) plus the asker never chose an answer so the question was never solved.
Here's my code
const express = require("express");
const db = require("mysql");
const app = express();
const bodyParser = require("body-parser");
const multer = require("multer"); // v1.0.5
const upload = multer(); // for parsing multipart/form-data
const http = require("http");
const path = require("path");
app.set("view engine", "jade");
app.set("views", path.join(__dirname));
console.log("before");
app.listen(8000, () => {
console.log("Server started!");
console.log("within");
});
console.log("after");
app.use(bodyParser.json()); // for parsing application/json
app.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded
app.post("/", function(req, res) {
console.log("hit here in post");
res.render("index.jade", {});
console.log("hit here in post");
res.json({ name: "John" });
res.status(500).json({ error: "message" });
res.end();
});
app.get("/", function(req, res) {
res.render("index.jade", {});
console.log("hit here in get");
console.log(req.body);
});
Here's the output.
before
after
Server started!
within
hit here in get
{}
I even tried to wrap the app sets and uses in app.configure like the asker of the other question to see if that was the issue but that configure function doesn't seem to exist anymore because I got an error about it.
Also I should probably note. My routing here is correct. I haven't made a views subfolder yet so that's why I have it written as it is.
Update
I think I may have spotted the issue but I don't understand why it's occurring. In the network tab of the browser I see that GET is getting 404 error because of a favicon.ico request but I don't understand where that request is coming from. I've seen the serve-favicon npm module to support it but didn't want to added because I never intended to add a favicon image to my server. I don't even understand how that would work.
Reply to last comment by James
What do you mean by I configure the middleware after it has started? Are you referring to the fact that the post method is written after port listening has started? Also if that's the reason why post isn't executing how come the get method executes regardless of that? I'm not holding back any server code aside from code I currently have commented out for the moment but that code I posted is my main index.js file and it's the only file I modified from the standard npm init project. I haven't setup any routes because I don't see the need to do so (even when I add react since my project is simple in concept of communication between reactjs, nodejs and a database "hence my frustration") which is why I'm trying to have get and post only access the root directory.
favicon is automatically requested by the browser. it is the icon used in the browser tab or url address bar
Add this, before app.get():
app.all('/', function(req, res, next) {
console.log({method: req.method, url: req.url});
next();
});
I am looking to capture all of the data from any request (images, fonts, css, js, etc) on my website so that I can capture the file details, specifically the file name and file size. I have found almost an identical question/solution:
Node.js : How to do something on all HTTP requests in Express?
But the solution appears to be deprecated with Express v4. Is there a simple solution to do this? As another approach I have tried the below solution with no luck:
var express = require("express");
var path = require("path");
var port = process.env.PORT || 3000;
var app = express();
var publicPath = path.resolve(__dirname, "public");
app.use(express.static(publicPath));
app.get("/", function(req, res){
// I want to listen to all requests coming from index.html
res.send("index.html");
});
app.all("*", function(){
// can't get requests
})
app.listen(port, function(){
console.log(`server listening on port ${port}`);
});
Also I am not looking to do this from Fiddler/Charles because I am looking to display this data on my site.
Express routes are predicated on order. Notice the answer that you linked in your question has the middleware defined, and used before all other routes.
Secondly you're trying to implement something that requires middleware, not a wildcard route. The pattern in link you provided in your question is not deprecated according to their docs.
app.use(function (req, res, next) {
// do something with the request
req.foo = 'testing'
next(); // MUST call this or the routes will not be hit
});
app.get('/', function(req, res){
if (req.foo === 'testing') {
console.log('works');
}
res.send("index.html");
});