在子目录中托管应用程序时ExpressJS API路由

时间:2020-03-28 02:09:42

标签: node.js express

我在根目录托管了一个应用,我想使用proxypass等将这个新应用托管在子目录/ rps中。一切正常,除了当我尝试调用api时,在路由中出现404错误,例如{ {3}}。前端应用程序基本上是从express的公共文件夹中静态提供的。

对任何想法持开放态度,我可能会做错或替代的方法。我真的很想为这个小型应用程序没有新的服务器,也无法将其构建到现有的应用程序中。当然,这些路由是在本地运行的,只是当我在服务器上的奇怪情况下托管时不是这样。

查看代码:

(服务器)index.js:

const config = require('./config.js');    

const app = express()
const port = process.env.PORT || 5000;   

var indexRouter = express.Router();    

const posts = require('./routes/api/posts')

indexRouter.use('/api/posts', posts)    

app.use(express.static(__dirname+ '/public'))

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

app.use(config.baseUrl, indexRouter);

(服务器)config.js:

module.exports  = {
    baseUrl: '/rps/',
}

(服务器)./routes/api/posts.js:

const router = express.Router()

router.post('/', (req, res) => {
    //gets my thang in action...
})

module.exports = router

(客户端)main.js:

axios.post('/api/posts/', { //  /rps/api/posts ??
    stuff: things,    
})
.then(function (response) {
    // do something else
})
.catch(function (error) {
    console.log(error);
})

提前谢谢!

0 个答案:

没有答案