通过Express访问静态内容和API

时间:2018-08-23 20:57:29

标签: node.js api express

我在/api有一个Express REST API,我想在/ui上显示一个前端。我有这个:

api.js

const STATIC_FILES_PATH = path.resolve(__dirname, '..', 'frontend', 'build');
app.use(express.static(STATIC_FILES_PATH));
app.get('/ui', (_, res) => {
    res.sendFile(path.resolve(STATIC_FILES_PATH, 'index.html'));
});

app.get('/api/stuff', (req, res) => {
    //do stuff
});

导航到/api/stuff时,仍然看到前端而不是API响应。无论URI是什么,它始终显示前端网页。

我在做什么错了?

编辑

这是我的项目结构:

/api
    api.js 
/frontend
    /build
        index.html

当我导航至/api/stuff时,在Chrome控制台中,我看到了 HTTP 304 !它将我重定向到前端(已缓存),而不是向我显示JSON结果(API响应)。

2 个答案:

答案 0 :(得分:0)

添加此中间件之后:

app.get('/*', (req, res, next) => {
    res.setHeader('Last-Modified', (new Date()).toUTCString());
    next();
});

工作正常。似乎Express正在缓存内容。谢谢大家!

答案 1 :(得分:-1)

使用此代码段更改您的代码,它已通过测试,可以正常工作。

api.js

const express = require('express');
const app = express();
const path = require('path');

const STATIC_FILES_PATH = path.resolve(__dirname, 'frontend', 'build');

app.use(express.static(STATIC_FILES_PATH));

app.get('/ui', (req, res, next) => {
    res.sendFile(path.resolve(STATIC_FILES_PATH, 'index.html'));
});

app.get('/api/stuff', (req, res, next) => {
    res.json({title: 'staff'});
});

app.listen(3000);