【发布时间】:2021-11-09 00:43:08
【问题描述】:
我正在开发一个简单的 MERN 应用。我正在尝试连接两端并在服务器 onSubmit() 上发布数据。我可以直接访问服务器 URL。但是,当我从 React 页面请求它时,我得到了 POST http://localhost:1337/api/register 404 (Not Found)。 任何形式的帮助将不胜感激 谢谢
服务器/index.js
const express = require('express')
const app = express()
const cors = require('cors')
app.use(cors())
app.use(express.json())
app.get('/api/register', (req, res) =>{
console.log(req.body)
res.json({status:'ok'})
})
app.listen(1337,() =>{
console.log('Server started on 1337')
})
client/App.js
import './App.css';
import {useState} from 'react';
function App() {
const [name, setName] = useState('')
const [email, setEmail] = useState('')
const [password, setPassword] = useState('')
async function registerUser(event){
event.preventDefault()
const response = await fetch('http://localhost:1337/api/register',{
method:'POST',
headers:{
'Content-Type': 'application/json',
},
body:JSON.stringify({
name,
email,
password
}),
})
const data = await response.json()
console.log(data)
}
return (
<div>
<h1>Register</h1>
<form onSubmit = {registerUser}>
<input
value = {name}
onChange = {(e)=> setName(e.target.value)}
type="text"
placeholder="Name"/>
<br/>
<input
value = {email}
onChange = {(e)=> setEmail(e.target.value)}
type="email"
placeholder="Email"/>
<br/>
<input
value = {password}
onChange = {(e)=> setPassword(e.target.value)}
type="password"
placeholder="Password"/>
<br/>
<input type = "submit" value = "Register"/>
</form>
</div>
);
}
export default App;
谢谢
【问题讨论】:
-
app.get('/api/register'->app.post('/api/register'
标签: node.js reactjs express mern