【发布时间】:2020-11-08 11:12:51
【问题描述】:
我有一个在提交表单时发出 POST 请求的应用程序。但是当请求在服务器上时,我无法获取请求的正文。
这是我的 ReactJS 代码:
const onSubmit = async event => {
try {
event.preventDefault()
const response = await fetch('/api/auth/login', {
method: 'POST',
mode: 'no-cors',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ email, password })
})
const result = await response.json()
} catch (e) {
console.error(e)
}
}
return (
<>
<h1>Authorisation</h1>
<form onSubmit={onSubmit}>
<input name="email" value={email} onChange={e => setEmail(e.target.value)} />
<input name="password" value={password} onChange={e => setPassword(e.target.value)} type="password"/>
<button type="submit">Submit</button>
</form>
</>
)
在我的后端我有 Express:
app.use(express.json())
const login = async (req, res) => {
try {
console.log(req.body) // here is always {}
const {email, password} = req.body
/*some code*/
} catch (e) {
console.log('Login error: ' + e)
}
}
router.post('/login', login)
app.use(router)
【问题讨论】:
-
你能从快递服务器发布完整的代码吗?你在哪里定义路由 /login?
-
前端代码看起来不错。请发布完整的快递端服务器代码。我认为你在那里遗漏了一些东西。
标签: node.js reactjs express fetch