javascript - 我对 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。
有没有办法解决这个问题?
谢谢你。
解决方案
要使用 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')
})
请注意:
/*
路由在 api 之后,以便所有与先前路径不匹配的路由,呈现您的 SPA 页面- 您需要
*
在 SPA url 模式中使用,因此当您路由到/user
它时会呈现 SPA 页面,然后在客户端上呈现user
页面 api
前缀,这将区分您的 api 和 SPA 路径
推荐阅读
- 2sxc - 仅获得草稿选项 - 没有“显示此项目”
- excel - Excel中动态改变数据连接路径
- konvajs - konvajs 加倍画布(缓冲画布)
- c - 多线程完美数字
- c# - 当文本跨越多个 OpenXML 元素时,如何在 Office OpenXML 中进行字符串替换?
- sql - SQL Server 记录计数差异
- java - 执行 Maven 时出错 - 不可解析的设置 settings.xml
- php - Laravel - 计算另一个 file.blade.php 上的行数表
- python - VSCode 和 Python 扩展:导航到符号非常非常慢
- openlayers-5 - 在 openlayers 5 中创建大圆圈