API接收未定义的数据



我是JS和反应的新手,但我试图将字符串传递给我的API,然后对所述字符串进行分析并传递回情感得分。然而,当我传递数据时,而在我的API的控制台中,字符串出现在'body'中,API声明'Description'未定义,导致API抛出错误。

api.js

const express = require('express');
const app = express()
app.use(express.json());
app.post('/', function (req, res) {
console.log('body is:', req.body);
const {description} = req.body;
console.log('Description is:', description);
var Analyzer = require('natural').SentimentAnalyzer;
var stemmer = require('natural').PorterStemmer;
var analyzer = new Analyzer("English", stemmer, "afinn");
const sentiment = analyzer.getSentiment(description.split(' '));
console.log('Sentiment is:', sentiment);
res.json(JSON.stringify({sentiment}))
})
app.listen(3000, () => {
console.log('listening on port 3000');
});

diary.js包含post函数和API调用

async function makePostRequest (diaryText) {
let payload = { Description: diaryText };
let res = await axios.post('http://localhost:3000/', payload);
let data = res.data;
console.log("This is the data returned in the post function:",data);
}
makePostRequest("testText").then(response => {
console.log("Data returned from the function call:", response);
}).then(error => {
console.error(error.response.data);
});

这是执行上述代码时控制台的输出:

body is: { Description: 'testText' }
Description is: undefined
TypeError: Cannot read property 'split' of undefined
at /Users/ddavies/Desktop/Desktop Storage/programming/MSc_App/api.js:14:54
at Layer.handle [as handle_request] (/Users/ddavies/Desktop/Desktop Storage/programming/MSc_App/node_modules/express/lib/router/layer.js:95:5)
at next (/Users/ddavies/Desktop/Desktop Storage/programming/MSc_App/node_modules/express/lib/router/route.js:137:13)
at Route.dispatch (/Users/ddavies/Desktop/Desktop Storage/programming/MSc_App/node_modules/express/lib/router/route.js:112:3)
at Layer.handle [as handle_request] (/Users/ddavies/Desktop/Desktop Storage/programming/MSc_App/node_modules/express/lib/router/layer.js:95:5)
at /Users/ddavies/Desktop/Desktop Storage/programming/MSc_App/node_modules/express/lib/router/index.js:281:22
at Function.process_params (/Users/ddavies/Desktop/Desktop Storage/programming/MSc_App/node_modules/express/lib/router/index.js:335:12)
at next (/Users/ddavies/Desktop/Desktop Storage/programming/MSc_App/node_modules/express/lib/router/index.js:275:10)
at /Users/ddavies/Desktop/Desktop Storage/programming/MSc_App/node_modules/body-parser/lib/read.js:130:5
at invokeCallback (/Users/ddavies/Desktop/Desktop Storage/programming/MSc_App/node_modules/raw-body/index.js:224:16)

对象键敏感,Description=/=description

const {Description} = req.body;

最新更新