使用正文获取与不使用正文获取(反应,表达)



我是 Web 开发的新手,并且在附加了 json 正文的获取请求时遇到了一些问题。现在,如果我在没有正文的情况下进行 fetch 调用,fetch 将连接到我的 api(记录它已连接到的 api(,从我的数据库中检索值,并将它们毫无问题地发送回前端。但是,当我将正文对象作为第二个参数添加到我的获取请求时,我的获取永远不会连接到 api。没有输出任何错误,它只是等待,我的 api 永远不会记录它已连接到。

这是代码。这有效:

//this.props.chosenInterests is an object
async sample(){
//url-friendly string
const university = this.props.chosenUniversity.replace(/s/, '+');
const query = '/interest/' + university;
try{
const response = await fetch(query, {});
if(response.ok){
const jsonResponse = await response.json();
globalVar = jsonResponse;
this.forceUpdate();
}
else{
throw new Error('Request Failed!');
}
}
catch (error){
console.log(error);
}
}

虽然这不会:

//this.props.chosenInterests is an object
async sample(){
//url-friendly string
const university = this.props.chosenUniversity.replace(/s/, '+');
const query = '/interest/' + university;
try{
const response = await fetch(query, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
},
body: JSON.stringify(this.props.chosenInterests)
});
if(response.ok){
const jsonResponse = await response.json();
globalVar = jsonResponse;
this.forceUpdate();
}
else{
throw new Error('Request Failed!');
}
}
catch (error){
console.log(error);
}
}

这是我的 api:

//already mounted router at /interest
interestRouter.get('/:university', (req, res, next) => {
const university = req.params.university.replace(/+/g, ' ');
console.log('Connected.');
db.all('SELECT * FROM Table WHERE Table.university = $university', {$university : university},
(error, result) => {
if(error){
next(error);
}
else{
res.json(result);
}
}
)
});

任何帮助将不胜感激。我只是对为什么我没有收到错误或任何东西感到困惑。

POST失败的原因是您的快速脚本正在寻找 GET,而不是 POST。如果将其更改为以下内容:

interestRouter.post('/:university', (req, res, next) => {...

然后你可以在 req.body 中看到 POST 的正文。

最新更新