【发布时间】:2019-12-21 13:44:08
【问题描述】:
我是 Web 开发新手,在发出带有 json 正文的 fetch 请求时遇到了一些问题。现在,如果我在没有正文的情况下进行 fetch 调用,则 fetch 会连接到我的 api(记录它已连接到的日志),从我的数据库中检索值,并将它们发送回前端而不会出现问题。但是,当我将 body 对象作为第二个参数添加到我的 fetch 请求时,我的 fetch 永远不会连接到 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);
}
}
)
});
任何帮助将不胜感激。我只是对为什么我没有收到错误或任何东西感到困惑。
【问题讨论】:
标签: reactjs express async-await fetch