【问题标题】:Does react router override URL Routing of app.get('/ping'?反应路由器是否覆盖 app.get('/ping' 的 URL 路由?
【发布时间】:2020-05-07 14:36:48
【问题描述】:

我目前有一个共享主机 (CPanel),它为客户端代码提供 Node.JS 的静态构建。在同一来源和共享主机上,我有一个快速服务器正在运行,如下所示:

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

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

// This doesn't work
app.get('/ping', (req, res) => {
  return res.send('pong')
})

app.use(express.static(path.join(__dirname, 'build')))


app.get('/', (req, res) => {
  res.sendFile(path.join(__dirname, 'build', 'index.html'))
})

app.listen(8080) (req, res) => {
  return res.send('pong')
})

app.use(express.static(path.join(__dirname, 'build')))

// This serves out the static build of the client side code (App.js) - and works
app.get('/', (req, res) => {
  res.sendFile(path.join(__dirname, 'build', 'index.html'))
})

app.listen(8080)

我正在尝试为服务器端创建一个 API 以与客户端交互。当我访问根“/”时,主应用程序可以完美运行。但是,当我尝试访问 API 的这一部分时,我似乎无法让这段代码在服务器端工作:

app.get('/ping', (req, res) => {
      return res.send('pong')
    })

当我使用“/ping”访问 URL 时,它只会给我一个空白屏幕,而不会说“pong”。但是,在静态构建中,我使用的是 BrowserRouter,当我访问 URL 中的“/rooms/id”时,它完美地为页面分配了一个 URL:

 function App() {
  return (

    <BrowserRouter>
      <Switch>
        <Route path="/" exact component={CreateRoom} />
        <Route path="/room/:roomID" component={Room} />
      </Switch>
    </BrowserRouter>
  );
}

此客户端代码是否与我的服务器端代码冲突?我如何获得一个 API 来为我的客户端和服务器端的东西提供相同的来源?

【问题讨论】:

    标签: node.js api express react-router url-routing


    【解决方案1】:

    解决了:

    我需要一个名为“ping”的根目录中的文件夹。

    这是我第一次构建 API,所以希望我能正确地做到这一点!

    【讨论】:

      猜你喜欢
      • 2018-03-26
      • 2021-12-13
      • 2016-07-12
      • 2020-05-18
      • 2023-03-26
      • 2018-01-14
      • 2017-12-16
      • 2018-05-30
      • 1970-01-01
      相关资源
      最近更新 更多