Javascript 我可以在react中的单个组件中执行多次提取吗?
我使用react作为前端,express.js作为后端。我对这两个框架都不熟悉。我有一个名为Papers的组件,我试图首先通过fetchpost将一些文档上传到后端服务器,然后在服务器端执行一些操作,然后在同一个处理程序中尝试从服务器返回结果。我的处理程序代码如下所示:Javascript 我可以在react中的单个组件中执行多次提取吗?,javascript,reactjs,express,Javascript,Reactjs,Express,我使用react作为前端,express.js作为后端。我对这两个框架都不熟悉。我有一个名为Papers的组件,我试图首先通过fetchpost将一些文档上传到后端服务器,然后在服务器端执行一些操作,然后在同一个处理程序中尝试从服务器返回结果。我的处理程序代码如下所示: handleDrop(files) { var data = new FormData(); alert((files[0]) instanceof File);
handleDrop(files) {
var data = new FormData();
alert((files[0]) instanceof File);
files.forEach((file, index) => {
data.append('file' + index, file);
});
fetch('/file_upload', {
method: 'POST',
body: data
});
// the second fetch would crash the app.
/*fetch('/file_upload').then(function(data){
return data.json();
}).then( json => {
this.setState({
papers: json
});
console.log(json);
});*/
}
get方法的express后端代码为:
app.get('/file_upload', function(req, res){
// testing
res.send({name:"lol"});
});
现在的问题是第二次抓取会使express应用程序崩溃。由于我是新的反应和表达,有人能给我一些提示,如果我这样做是正确的吗?谢谢
链接到服务器代码:如果您想发布帖子,Express代码应该如下所示:
app.post('/file_upload', function(req, res){
// testing
res.send({name:"lol"});
});
您只需要执行一次fetch调用。响应({name:'lol'}
)将在承诺中:
handleDrop(files) {
var data = new FormData();
alert((files[0]) instanceof File);
files.forEach((file, index) => {
data.append('file' + index, file);
});
fetch('/file_upload', {
method: 'POST',
body: data
}).then(function(data){
return data.json();
}).then( json => {
this.setState({
papers: json
});
console.log(json); // logs {name: 'lol'}
});
}
首先,您将发送POST请求,并显示GET的服务器端部分。第二,您可以使用响应体在相同的获取中获取答案request@GeorgiyDubrov很抱歉造成混乱,发布方法有点长,所以我没有发布。现在在github链接上。嗨,谢谢!因此,我尝试在我的post方法中添加res.send,并根据您的建议修改了我的react fetch代码。这次没有错误,但我什么也没得到?你知道为什么会这样吗?谢谢@Rockingchief您能否确认,即使使用一个简单的
应用程序,您也不会得到任何回报。post
方法,就像我提到的,除了发送一个简单的回复“lol”之外,没有其他作用?你发送的Github链接中的app.post
相当复杂,我宁愿排除这种复杂情况。因此我将该部分注释掉,但仍然得不到任何回报。@Rockingchief你能试着让你的回执行看起来像这样吗?我启动了一个服务器,它应该以完全相同的方式返回数据fetch('https://IncomparableGleefulSpecialist--MitchLillie.repl.co/testing', {
所以我只是修改了我的获取代码,但仍然没有显示任何内容。我不确定您是否可以在post请求中返回数据?因为我觉得这应该是get请求的工作?再次感谢!