简体   繁体   中英

Handling route requests between React and Express

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:

  1. With regards to this line:

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

  1. How can I send a response back to the react app to tell it for example that the user exists and the password is correct? I have already made the mysql query that checks this and updates a variable in express I just need to then send the response, perhaps the value of that variable that will then tell react to go to the index page. However res.send(variable) does not seem to be sending the variable to react and the login form stays stagnant after it is submitted.

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"})
       })
    ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM