无法在 cpanel 上获取 Nodejs Express 应用程序。但在 GET 请求中使用 * 时有效

SKR*_*123 2 cpanel node.js namecheap

我已经在带有 namecheap 托管的 cpanel 上部署了带有express的nodejs。我已经使用了在 cpanel 中创建 Nodejs 应用程序的默认提供的服务。问题是我的 GET 请求无法正常工作。如果我使用“/”或“routename”作为路线,我会收到 Cannot GET 消息。

const express = require('express')

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

app.use(express.json())
app.use(
cors({
    origin:'*'
})
)


app.get("/", (req, res) => { 
 console.log('req came')
 res.send({ message: "Works!" });
});


app.listen('8080', ()=>{
 console.log('Server started on port 8080')
})
Run Code Online (Sandbox Code Playgroud)

但如果我改变路线

app.get("*", (req, res) => { 
 console.log('req came')
 res.send({ message: "Works!" });
});
Run Code Online (Sandbox Code Playgroud)

通过将“/”替换为“*”(忽略星号周围的空格,因为它没有在没有空格的情况下渲染)它可以工作。但问题是,由于“*”重定向到每个请求,我无法使用其他路由。我也尝试过删除端口并仅使用

app.listen()
Run Code Online (Sandbox Code Playgroud)

但结果是一样的。什么可能导致此问题?也许旅客档案有问题?我还尝试根据 NodeJS '/' 主路由的建议在 .htaccess 之上添加以下内容,但其余路由不起作用(CPanel 共享托管),但没有积极的结果。

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteBase /
RewriteRule ^server/(.*)?$ https://127.0.0.1:8080/$1 [P,L]
Run Code Online (Sandbox Code Playgroud)

Nodejs版本:10.24.1

"body-parser": "^1.20.0",
"cors": "^2.8.5",
"express": "^4.18.1",
Run Code Online (Sandbox Code Playgroud)

已联系 Namecheap 支持来解决此问题。他们提到该应用程序严重依赖星号来工作。不确定是否属于这种情况。

SKR*_*123 5

我找到了解决方案,感谢这个资源How to fix the Node.js error: \xe2\x80\x9cCannot GET\xe2\x80\x9d URL

\n

问题是我必须使用应用程序目录名称作为基本 url。所以它会像

\n
app.get("/appdirectoryname/", (req, res) => { \n console.log(\'req came\')\n res.send({ message: "Works!" });\n});\n
Run Code Online (Sandbox Code Playgroud)\n

要使用不同的路线,只需将其附加到基本路线名称即可。例如

\n
app.get("/appdirectoryname/routename", (req, res) => { \n console.log(\'req came\')\n res.send({ message: "Works!" });\n});\n
Run Code Online (Sandbox Code Playgroud)\n