I am creating an app with login and registration functionality with React and Express. I am using Formik to handle the form data as well as to post it:
> const initialValues={{username:"", email:"", password:""}}
onSubmit ={ async (values, { setSubmitting }) => {
const value = values.username+'/'+values.email+'/'+values.password;
const res = await fetch(`http://localhost:5000/newuser/${value}`, {
method: 'GET',
mode: 'cors',
headers: {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*'
}}).then(response => response.json());
console.log(res);
values = initialValues;
setSubmitting(false);
}
This is then sent to the express application to the following route:
> app.get('/newuser/:username/:email/:password', (req, res) => {
const username = req.params.username;
const email = req.params.email;
const password = req.params.password;
let sql = `Insert into users (username, useremail, userpass) values ('${username}', '${email}', '${password}')`;
query = db.query(sql, (err, results) => {
if(err){throw err;}
res.send("New user added you can login now");
});
});
I am able to save these users to the database however I have the following 2 questions about this code, which I was able to piece together from various different videos, tutorials, questions and docs:
app.get('/newuser/:username/:email/:password', (req, res)
This is the only way I can get the form data into express, if I do not include the semi-colons and call these values using req.params, I get a "404 not found error" because the 3 values are empty. If I try and access them via req.body they still appear to be empty. I have tried to JSON.stringify them and I am using body-parser in the express app. My question is how can I access these 3 values(username, email, password) with req.body? Also is there a specific way I should format them if I want access this route from my browser, for example http://localhost:5000/users?username&email&password
To access the body use method:"POST"
rather than GET.
let response = await fetch(`http://localhost:5000/newUser`, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify(values),
})
if (response.errors) {
console.error(response.errors)
}
let responseJson = await response.json()
if (responseJson['message']) {
console.log(responseJson['message'])
}
Server side use something like this:
import cors from 'cors'
...
let app = express()
.use(cors())
.post('/newUser', (req, res) => {
let {username, email, password} = req.body
...
// If all ok
res.status(200).send({message: "User created"})
// If there's an issue
res.status(500).send({message: "oups"})
})
...
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다