首页 > 解决方案 > 我对 node.js express 中的路由有一些问题

问题描述

我的应用是使用反应的 SPA

我正在尝试在 node.js 中使用 express 构建 API

所以我的服务器代码是

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

const PORT = 80;
app.listen(PORT, () => {
    console.log('connected')
}}

app.get('/', (req, res) => {
    res.sendFile(__dirname + '/public/index.html')
})

//api
app.get('/user', .....
   res.json(~~~)
app.post('/user', .........
   res.json(~~~~)

因为我的客户是水疗中心(反应),

服务器代码中只有一个“sendFile”。

剩下的就是 API,它返回 JSON。

所以我只想使用关于 fetch 或 ajax 方式的 API

但是目前的情况是,如果客户端直接访问api url,

浏览器可以看到 json 而不是我的 spa。

有没有办法解决这个问题?

谢谢你。

标签: javascriptnode.jsreactjsexpresssingle-page-application

解决方案


要使用 SPA 方式的路由,您需要将页面 url 和 api url 分开:

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

const PORT = 80;
app.listen(PORT, () => {
    console.log('connected')
}}

//api
app.get('/api/user', .....
   res.json(~~~)
app.post('/api/user', .........
   res.json(~~~~)

app.get('/*', (req, res) => {
   res.sendFile(__dirname + '/public/index.html')
})

请注意:

  1. /*路由在 api 之后,以便所有与先前路径不匹配的路由,呈现您的 SPA 页面
  2. 您需要*在 SPA url 模式中使用,因此当您路由到/user它时会呈现 SPA 页面,然后在客户端上呈现user页面
  3. api前缀,这将区分您的 api 和 SPA 路径

推荐阅读