im trying to send data from my frontend to my backend (React and NodeJS)
export default function UserFormPage(){
const [ username, setUsername ] = useState("")
const [ password, setPassword ] = useState("")
// MOVE TO A SERVICE
const setUsernameValue = (e) => {
setUsername(e.target.value)
}
const setPasswordValue = (e) => {
setPassword(e.target.value)
}
// MOVE TO A SERVICE
const handleSubmit = (e) => {
e.preventDefault()
const data = {username, password}
console.log(data)
return fetch("http://localhost:8080/users", {
method: "POST",
mode: "no-cors",
headers: { "Content-Type" : "application/x-www-form-urlencoded"},
body: data
})
}
return(
<div>
<form encType="application/x-www-form-urlencoded" onSubmit={handleSubmit}>
<input value={username} onChange={setUsernameValue} name="username" type="text"/>
<input value={password} onChange={setPasswordValue} name="password" type="text" /*CAMBIAR TYPE A PASSWORD*//>
<button type="submit">Submit</button>
</form>
</div>
)
}
and my backend is
app.post("/users", (req, res) => {
console.log(req.body)
res.send("working");
});
But the console.log is only displaying an empty object. I tested sending a POST request with Postman and it works fine so the problem is in my frontend
here is the correct implementation on react and nodejs express api with cors.
with this you can get the body object on server side whatever you put on the input boxes:
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var cors = require('cors');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(cors());
app.use('/', indexRouter);
app.use('/users', usersRouter);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
app.listen(8081,function(){
console.log("server is running on port 8081");
});
module.exports = app;
import React, { useState } from 'react';
import './App.css';
function App() {
const [username, setUsername] = useState('');
const [password, setPassword] = useState('');
const setUsernameValue = (e) => {
setUsername(e.target.value);
};
const setPasswordValue = (e) => {
setPassword(e.target.value);
};
const url = 'http://localhost:8081/users';
const header = { 'Content-Type': 'application/json' };
//FETCH DOCS:
//https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API
//https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
const handleSubmit = async(e) => {
e.preventDefault();
const data = { user: username, pass: password };
await fetch(url,{
method: 'POST', // *GET, POST, PUT, DELETE, etc.
cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
headers: header,
body: JSON.stringify(data) // body data type must match "Content-Type" header
}).then((response)=>{
console.log('finish api call - response:::',response);
}).catch((error)=>{
console.log('something wrong:::',error);
});
};
return (
<div>
<form onSubmit={handleSubmit}>
<input
value={username}
onChange={setUsernameValue}
name='username'
type='text'
/>
<input
value={password}
onChange={setPasswordValue}
name='password'
type='password'
/>
<button type='submit'>SEND</button>
</form>
</div>
);
}
export default App;