简体   繁体   中英

Express set header content response type

I am trying to set header content type to be application/json for universal links from IOS, but still response is with

Content-Type: application/octet-stream

but should be

'Content-Type', 'application/json'

My simple server.js looks like follows:

// Install express server
const express = require('express');
const path = require('path');
const app = express();
// Serve only the static files form the dist directory
app.use(express.static(__dirname + '/dist'));
app.use(function (req, res, next) {
  res.setHeader('Content-Type', 'application/json');
  res.header('Content-Type', 'application/json');
  next();
});

app.get(
  '/dist/.well-known/apple-app-site-association',
  function (req, res, next) {
    console.log('it is not console.logged');

    res.header('Content-Type', 'application/json');
    res.sendFile(
      path.join(__dirname + '/dist/.well-known/apple-app-site-association')
    );
    res.setHeader('Content-Type', 'application/json');
    req.header('Content-Type', 'application/json');
  }
);
app.get('/*', function (req, res) {
  console.log('can log here');

  res.setHeader('Content-Type', 'application/json');
  res.sendFile(path.join(__dirname + '/dist/index.html'));
  res.header('Content-Type', 'application/json');
});

// Start the app by listening on the default Heroku port
app.listen(process.env.PORT || 8080);

How to set header conent type to be application/json?

Since you are using express.static , which is the first middleware in your code, requests that match the files in the static folder will be handled by express.static . The files in .well-known probably do not have a .json extension, hence the content type will be inferred as application/octet-stream as this is the default .

What you could do is simply add the following middleware before the static middleware to ensure that all .well-known files will be served with application/json content type:

app.use('/.well-known',(req, res, next) => {
    res.header('Content-Type', 'application/json');
    next();
});
app.use(express.static(__dirname + '/dist'));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM