Sunday, October 20, 2013

NodeJS Express Automatic Content Type

Try this in a NodeJS Express application. Add a route as shown below and take a look at what the web page shows:
app.get('/mytest', function(req,res){
    var testdata = {
        segment: 'Five',
        value: '42',
        environment: 'development'
Before you go to this page in your browser, probably something like http://localhost:3000/mytest you should bring up the Developer Tools, on Chrome you can do this by hitting F12 or Ctrl+Shift+i.

In the browser you will see:
  "segment": "Five",
  "value": "42",
  "environment": "development"
In the Developer Tools take a look at the Response Headers in the Headers section. You will see that Content-Type is set to application/json; charset=utf-8

Now let's change the mytest function to the following:
app.get('/mytest', function(req,res){
    res.send('this is my data');
The browser will now show you:

this is my data

If you look at the developer tools you'll see that the Content-Type is now text/html; charset=utf-8

NodeJS/Express detected the type of data that you're sending back to the browsers and adjusted the Content-Type appropriately.

No comments:

Post a Comment