【问题标题】:Express set header content response type快速设置标头内容响应类型
【发布时间】:2021-05-23 05:28:22
【问题描述】:

我正在尝试将来自 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);

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

【问题讨论】:

    标签: javascript ios node.js express


    【解决方案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'));
    

    【讨论】:

    • thx,但不起作用:(。我也尝试了不同的路径,但也不起作用app.use('/dist/.well-known/*', (req, res, next) => { console.log('hello world'); res.header('Content-Type', 'application/json'); next(); }); app.use(express.static(__dirname + '/dist')); ,但我什至无法在第一个 app.use() 中使用 console.log /跨度>
    • 从路径中删除dist ..如果它仍然不起作用,请显示您的请求,例如通过curl
    • 不,还是一样,不知道如何显示。 curl localhost:8080/.well-known/apple-app-site-association { "applinks": { "details": [ { "appID": "GF32XXXXX.lt.myApp", "paths": ["*"] } ] } }
    • 很奇怪,肯定可以在我的机器上运行。这是一个代码框的链接,它也可以在其中工作:codesandbox.io/s/exciting-rain-0znge。用https://0znge.sse.codesandbox.io/.well-known/apple-app-site-association提出请求
    • 不知道,但仍然有 Content-Type:application/octet-stream。我还尝试使用 docker 和 nginx 部署它。它在本地工作,但不能在 heroku 应用程序上运行。这是一个问题,也许你有一些想法stackoverflow.com/questions/66204473/…
    猜你喜欢
    • 2015-07-19
    • 2016-02-25
    • 2011-09-30
    • 1970-01-01
    • 2015-03-10
    • 2020-12-06
    • 1970-01-01
    • 1970-01-01
    • 2016-09-07
    相关资源
    最近更新 更多