I am developing a simple MERN app. I am trying to connect the both ends and post data on server onSubmit(). I am able to access the server URL directly.However, I am getting POST http://localhost:1337/api/register 404 (Not Found) when requesting it from React page. Any kind of help will be appreciated Thanks
server/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;
Thanks
CodePudding user response:
const express = require('express')
const app = express()
const cors = require('cors')
app.use(cors())
app.use(express.json())
app.use(express.urlencoded({ extended: false }));
app.post('/api/register', (req, res) =>{
console.log(req.body)
res.json({status:'ok'})
})
app.listen(1337,() =>{
console.log('Server started on 1337')
})
For the post request, we must tell our API requests that it is POST so we must initialize our request with the POST method.