Postman测试/api/sentiment端点时出现Cannot POST错误的技术求助
解决POST /api/sentiment时的Cannot POST错误
兄弟,我一眼就看出问题出在路由路径重复定义上,这是Express开发里很容易踩的小坑!另外还有个小细节需要补全,我一起帮你理清楚:
1. 核心问题:路由路径重复导致404
看你的server.js配置:
app.use('/api/sentiment', require('./app/routes/sentiment-analysis.routes'));
这里已经把sentiment-analysis.routes里的所有路由都挂载到/api/sentiment这个父路径下了。但你的路由文件里又写了:
router.post('/api/sentiment', (req, res) => { ... })
这就导致实际生效的路由是/api/sentiment/api/sentiment,而你在Postman里请求的是/api/sentiment,自然找不到对应的POST路由,返回Cannot POST错误。
修正方案
把路由文件里的路径改成根路径/即可:
const express = require('express'); const router = express.Router(); const getSentiment = require('../sentiment-analysis/sentimentAnalysis') // 只需要写 '/',父路径已经在server.js里定义好了 router.post('/', (req, res) => { const data = req.body.data const sentiment = getSentiment(data) return res.send({sentiment}) }) module.exports = router;
2. 补充修复:sentimentAnalysis.js缺少返回值
另外我注意到你的getSentiment函数最后计算了analyzed结果,但没有返回它!这样调用getSentiment(data)会得到undefined,前端收到的sentiment字段也是空的。需要补上返回语句:
function getSentiment(text){ if(!text.trim()) { return 0; } const lexed = aposToLexForm(text).toLowerCase().replace(/[^a-zA-Z\s]+/g, ""); const tokenized = tokenizer.tokenize(lexed) const correctSpelling = tokenized.map((word) => spellCorrector.correct(word)) const stopWordsRemoved = stopword.removeStopwords(correctSpelling) console.log(stopWordsRemoved) const analyzed = analyzer.getSentiment(stopWordsRemoved); console.log(analyzed) // 加上这行返回分析结果 return analyzed; }
测试验证
做完这两个修改后,在Postman里发送POST请求到http://localhost:8080/api/sentiment,请求体用JSON格式传入data字段,比如:
{ "data": "Wow this is fantastic!" }
应该就能正常返回 sentiment 分析结果了。
内容的提问来源于stack exchange,提问作者tza00
相关产品推荐
相关产品推荐

