Hiển thị các bài đăng có nhãn express. Hiển thị tất cả bài đăng
Hiển thị các bài đăng có nhãn express. Hiển thị tất cả bài đăng

Difference between res.setHeader and res.header in node.js

 javascript - How can I set response header on express.js assets - Stack Overflow

res.setHeader() is a native method of Node.js and res.header() is an alias of res.set() method from Express framework.

Documentation: res.setHeader()res.set()

This two methods do exactly the same thing, set the headers HTTP response. The only difference is res.setHeader() allows you only to set a singular header and res.header() will allow you to set multiple headers. So use the one fit with your needs.


res.set(field [, value])

Sets the response’s HTTP header field to value. To set multiple fields at once, pass an object as the parameter.

res.set('Content-Type', 'text/plain')

res.set({
  'Content-Type': 'text/plain',
  'Content-Length': '123',
  ETag: '12345'
})

Aliased as res.header(field [, value]).

multiple URLs to the same route

 https://stackoverflow.com/questions/47338471/express-routing-multiple-urls-to-the-same-route?rq=1


Instead of using an anonymous function as the route's controller, you can give it a name and pass the name to router.get. You can then have several router.gets that points to the same function.

function slugController(req, res, next) {

  if (!req.params.slug) {
    req.params.slug = 'home'
  }

  getData(slug, function(err, data){

    res.render('index', data)

  });

});

router.get("/page-slug-name", slugController);
router.get("/page-slug-name/amp", slugController);
router.get("/", slugController);
router.get("/amp", slugController);

This works best if there only are a couple of routes.

If you have a ton of routes you have to use the regex stuff that's mentioned in the manual. I don't see any pattern in your URLs though, so it's a bit hard to come up with a good solution using regex.

variable name contains dash creates problems for req.query for NodeJS Express?

https://stackoverflow.com/questions/22740821/get-variable-name-contains-dash-creates-problems-for-req-query-for-nodejs-expres

In javascript, object values can be accessed by using either . or []
When the key contains a dash, you cannot use the . notation because the - will be interpreted as "minus". This is not related to express, it's just how javascript works.
So you should use:
req.query["message-timestamp"]

Download a file from NodeJS Server using Express

Source:

Update

Express has a helper for this to make life easier.
app.get('/download', function(req, res){
  const file = `${__dirname}/upload-folder/dramaticpenguin.MOV`;
  res.download(file); // Set disposition and send it.
});

Old Answer

As far as your browser is concerned, the file's name is just 'download', so you need to give it more info by using another HTTP header.
res.setHeader('Content-disposition', 'attachment; filename=dramaticpenguin.MOV');
You may also want to send a mime-type such as this:
res.setHeader('Content-type', 'video/quicktime');
If you want something more in-depth, here ya go.
var path = require('path');
var mime = require('mime');
var fs = require('fs');

app.get('/download', function(req, res){

  var file = __dirname + '/upload-folder/dramaticpenguin.MOV';

  var filename = path.basename(file);
  var mimetype = mime.lookup(file);

  res.setHeader('Content-disposition', 'attachment; filename=' + filename);
  res.setHeader('Content-type', mimetype);

  var filestream = fs.createReadStream(file);
  filestream.pipe(res);
});
You can set the header value to whatever you like. In this case, I am using a mime-type library - node-mime, to check what the mime-type of the file is.
Another important thing to note here is that I have changed your code to use a readStream. This is a much better way to do things because using any method with 'Sync' in the name is frowned upon because node is meant to be asynchronous.

Express Application: How do I handle 404 responses?

Source: https://expressjs.com/en/starter/faq.html

In Express, 404 responses are not the result of an error, so the error-handler middleware will not capture them. This behavior is because a 404 response simply indicates the absence of additional work to do; in other words, Express has executed all middleware functions and routes, and found that none of them responded. All you need to do is add a middleware function at the very bottom of the stack (below all other functions) to handle a 404 response:
app.use(function (req, res, next) {
  res.status(404).send("Sorry can't find that!")
})
Add routes dynamically at runtime on an instance of express.Router() so the routes are not superseded by a middleware function.

How do I redirect in expressjs while passing some context?

Source: https://stackoverflow.com/questions/19035373/how-do-i-redirect-in-expressjs-while-passing-some-context


There are a few ways of passing data around to different routes. The most correct answer is, of course, query strings. You'll need to ensure that the values are properly encodeURIComponent and decodeURIComponent.
app.get('/category', function(req, res) {
  var string = encodeURIComponent('something that would break');
  res.redirect('/?valid=' + string);
});
You can snag that in your other route by getting the parameters sent by using req.query.
app.get('/', function(req, res) {
  var passedVariable = req.query.valid;
  // Do something with variable
});
For more dynamic way you can use the url core module to generate the query string for you:
const url = require('url');    
app.get('/category', function(req, res) {
    res.redirect(url.format({
       pathname:"/",
       query: {
          "a": 1,
          "b": 2,
          "valid":"your string here"
        }
     }));
 });
So if you want to redirect all req query string variables you can simply do
res.redirect(url.format({
       pathname:"/",
       query:req.query,
     });
 });
And if you are using Node >= 7.x you can also use the querystring core module
const querystring = require('querystring');    
app.get('/category', function(req, res) {
      const query = querystring.stringify({
          "a": 1,
          "b": 2,
          "valid":"your string here"
      });
      res.redirect('/?' + query);
 });
Another way of doing it is by setting something up in the session. You can read how to set it up here, but to set and access variables is something like this:
app.get('/category', function(req, res) {
  req.session.valid = true;
  res.redirect('/');
});
And later on after the redirect...
app.get('/', function(req, res) {
  var passedVariable = req.session.valid;
  req.session.valid = null; // resets session variable
  // Do something
});
There is also the option of using an old feature of Express, req.flash. Doing so in newer versions of Express will require you to use another library. Essentially it allows you to set up variables that will show up and reset the next time you go to a page. It's handy for showing errors to users, but again it's been removed by default. EDIT: Found a library that adds this functionality.
Hopefully that will give you a general idea how to pass information around in an Express application.

Renewing Facebook Graph API token automatically?

  Mã truy cập dài hạn https://developers.facebook.com/docs/facebook-login/guides/access-tokens/get-long-lived/ https://community.n8n.io/t/re...