如何使用fetch将JSON数据发送到node.js服务器?



我有一个node.js后端服务器。前端运行在Angular 10上。我想通过数据从前端到后端使用fetch

前端代码:
testmariadb($event: MouseEvent) {
return fetch('/api/customQuery', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({
sqlQuery: 'SELECT * FROM software'
})
})
}

后端代码

app.post('/api/customQuery', async (req, res) => {
let test = req.body['sqlQuery'] 
console.log(test)
})

我得到这个错误:

let test = req.body['sqlQuery'] 
^
TypeError: Cannot read properties of undefined (reading 'sqlQuery')
at /home/erwan/Documents/GitHub/serverAltertManager/index.js:90:22

我做错了什么?

是否正确使用中间件

const express = require('express');
const app = express();
app.use(express.json());
testmariadb() {
fetch('APIURL', {
method: 'POST',
headers: {'Content-Type': 'application/json; charset=UTF-8'},
body: JSON.stringify({
key: 'Value'
})
}).then((result)=>{
return result
})
}

最新更新