快速设置标头内容响应类型

时间:2021-02-20 11:11:43

标签: javascript ios node.js express

我正在尝试将标头内容类型设置为来自 IOS 的通用链接的 application/json,但仍然有响应

Content-Type: application/octet-stream

但应该是

'Content-Type', 'application/json'

我的简单 server.js 如下所示:

// 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);

如何设置头部内容类型为application/json?

1 个答案:

答案 0 :(得分:1)

由于您使用的是 express.static,这是您代码中的第一个中间件,因此与静态文件夹中的文件匹配的请求将由 express.static 处理。 .well-known 中的文件可能没有 .json 扩展名,因此内容类型将被推断为 application/octet-stream,因为这是 default

您可以做的只是在静态中间件之前添加以下中间件,以确保所有 .well-known 文件都将使用 application/json 内容类型提供:

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