【发布时间】:2020-01-10 07:58:34
【问题描述】:
我正在尝试使用带有 React 的 fetch 和带有 Node.js 的 Express 框架来设置异步 POST 请求。
提交表单后,我可以在服务器端看到 node.js 正在接收数据。
我的困难是,在客户端提交表单后,网页就像渲染了很长时间一样,并且浏览器在加载时显示Waiting for localhost...。
如果我在服务器端添加res.send('received POST data'),我会被重定向到localhost:9000/jobSearch,它会显示“收到的POST 数据”。
我想从localhost:9000/jobSearch 检索数据并将其显示在客户端localhost:3000 上,而无需重新加载页面。我已经读过使用 axios 或 jQuery 可能会更容易,但是我想只使用带有 Node.js 的 React 和 Express 来做到这一点。我复制了几个例子,但我无法让我的实现工作。我错过了什么吗?
反应:
App.js
import React, { Component } from 'react';
import { FormControl, Button } from 'react-bootstrap'
class App extends Component {
constructor(props) {
super(props);
this.state = {
jobSearch: {
jobTitle: '',
location: ''
}
}
}
onSubmit = (e) => {
e.preventDefault();
const { jobTitle, location } = this.state;
fetch('http://localhost:9000/jobSearch',{
method: "POST",
headers: {
'Content-type': 'application/json'
},
body: JSON.stringify(this.state.jobSearch)
}).then(res => res.json())
.then((result) => {
console.log('callback for the response')
})
}
render() {
return (
<form method="POST" action="http://localhost:9000/jobSearch">
<FormControl name="jobTitle"/>
<FormControl name="location"/>
<Button type="submit">Find Jobs</Button>
</form>
)
}
}
export default App;
Node.js:
jobSearch.js
var express = require('express');
var router = express.Router();
router.post('/', function(req, res, next) {
console.log('req.body here -> ', req.body)
});
module.exports = router;
【问题讨论】:
-
去掉方法和动作,把onSubmit放到表单或者按钮组件上
标签: node.js reactjs express asynchronous fetch