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
Related
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')
});
I have a node.js server that is forwarding API requests through to another server on a different port (so that auth cookies and the like make it across), and this has all worked great until the client has needed to upload a large file (> 100mb).
When I try to do that, if the file is over ~30mb the request never even reaches the far server (which will happily accept large files when connected to directly), so I'm pretty sure it's dying in node ... somewhere.
"use strict";
const http = require("http");
const port = process.env.FRONTEND_PORT || 13370;
const path = require("path");
const request = require("request");
const express = require("express");
const app = express();
const staticPath = path.join(__dirname, "/dist/");
app.set("port", port);
// Attempt to set some ridiculously high limits on things
app.use(express.urlencoded({parameterLimit: 1000000, limit: '10gb', extended: true}));
app.use(express.json({limit: '10gb'}));
// Serve files from this location
app.use(express.static(staticPath));
app.use(
'/api',
(req, res) =>
{
var url = "https://localhost:12121/api" + req.url;
req.pipe(request(url)).pipe(res);
console.log(res.statusCode);
console.log(res.statusMessage);
});
// If we hit any path that doesn't exist, instead serve up index.html and let react router handle it
app.get("*", (req, res) => { res.sendFile(path.join(__dirname, "/dist/index.html")); });
app.listen(app.get("port"), () => { console.log("listening"); });
As you can see, I've tried bumping up the limits (based on other SO answers I've seen) using:
app.use(express.urlencoded({parameterLimit: 1000000, limit: '10gb', extended: true}));
app.use(express.json({limit: '10gb'}));
...but this doesn't seem to be helping me in this case. I'm sure I'm missing something obvious, but I am extremely new to node.js (and, honestly, web development in general).
(It's also worth noting, the file is being sent through a basic XMLHttpRequest as POST, sending a File object through - nothing fancy going on there)
I have an express server in NodeJS. It has a POST request with console.logs inside of it. Where Can I find the console.logs?
const express = require('express');
const cors = require('cors');
const app = express();
app.use(cors());
app.use(express.json());
const PORT = 5000;
app.get('/', (req, res) => {
console.log("this appears in the browser");
});
app.post('/login', (req, res) => {
console.log("where do I see this text??");
});
app.listen(PORT, '0.0.0.0', function() {
console.log("Server started (this text appears in the terminal)");
});
I'm running the server from Command Prompt. console.logs that aren't within a request appear in it. Where do the console.logs in the POST request function appear? I ask because I would like to see what's going on with the logic inside a more sophisticated POST request.
When you run the Node.js server directly from cmd, it should start the server and listening to the port specified. Now, when you start to hit the route/s all the console.log o/p to the terminal window not to the browser console window. Check the image for reference.
It will appear in the same terminal that you put the server to run.
I just started my nodejs express template buy cors is not working.
I used npm install cors --save
here is the file:
var express = require('express');
var cors = require('cors');
var app = express();
app.use(cors());
var corsOptions = {
origin: 'https://example.com/',
optionsSuccessStatus: 200
};
app.get('/', cors(corsOptions), function(req, res, next) {
res.json({ message: 'hooray! welcome to our api!' });
});
app.get('/tt', function(req, res, next) {
res.json({ message: 'hooray! welcome to our api!' });
});
var port = process.env.PORT || 3030;
app.listen(port);
console.log('Magic happens on port ' + port);
Now with the above code when I access localhost:3030/tt or / I still see the content and I shouldn't
What's wrong with this.. I just lost like 2 hours working on this.. :(
At this time I would like not to use CORS, but in near future when my app is finished, I want to allow incoming calls only from my project, since this app will be my API.
The behavior you are describing seems is what I would expect.
CORS won't help you filter out incoming calls on the server. In this case the browser's CORS check won't kick-in as it appears you are directly typing in the URL in the browser. Browser does a CORS check only when the the webpage loaded from a particular domain tries to access/submit to a URL in a different domain.
A different way to think about CORS. CORS is intended to protect the user sitting in front of the browser, and not the server-code that is being accessed.
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");
});