Handling route requests between React and Express

Andy Golem

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.
Albert James Teddy

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] 삭제

에서 수정
0

몇 마디 만하겠습니다

0리뷰
로그인참여 후 검토

관련 기사

분류에서Dev

Regex in express route handler overriding default route

분류에서Dev

노드 express.Router (). route () 대 express.route ()

분류에서Dev

Node/Express - How to implement DELETE and PUT requests

분류에서Dev

Node express.Router (). route (/ verb / : optionalParameter)?

분류에서Dev

How to structure requests exception handling and check for 200 response?

분류에서Dev

Node.JS - Handling incoming requests with Async functions

분류에서Dev

Handling cross domain preflight AJAX OPTIONS requests with Spring MVC 4

분류에서Dev

Django persistent API connections between requests

분류에서Dev

Django - keeping parameters dictionary between requests

분류에서Dev

Laravel sessions don't remain between requests

분류에서Dev

Express Get route return error 500 : "Cast to ObjectId failed for value"

분류에서Dev

Express js, GET request to the same route for the second time always pending

분류에서Dev

route.js에서 Express Router 사용

분류에서Dev

ui route, node, express, 404 html 파일

분류에서Dev

Why React.Component is not displayed on a particular route?

분류에서Dev

React Router Default Route Redirect to / home

분류에서Dev

React Route Component TypeError : history is undefined

분류에서Dev

Rails session store to persist search params between requests

분류에서Dev

Create route between two networks in Google Cloud Compute Engine

분류에서Dev

Distinguish between arguments and react events

분류에서Dev

React Route로 인해 클래스 변경

분류에서Dev

Route에 의한 React Router 컨디셔닝

분류에서Dev

Nodejs Express에서 App Route가 작동하지 않습니다.

분류에서Dev

router.route와 일치하지 않는 Express.js 4 경로

분류에서Dev

Converting Express route with params from String ( '/page/:page' ) to RegExp ( /page/:page ) not working

분류에서Dev

Google 인증 콜백 Express Route에서 일반 사용자 차단

분류에서Dev

내 노드 변수 express 및 route 전역 화

분류에서Dev

Cannot post image file from React frontend to express and MySQL

분류에서Dev

Express 또는 React 및 DB 만있는 Electron

Related 관련 기사

  1. 1

    Regex in express route handler overriding default route

  2. 2

    노드 express.Router (). route () 대 express.route ()

  3. 3

    Node/Express - How to implement DELETE and PUT requests

  4. 4

    Node express.Router (). route (/ verb / : optionalParameter)?

  5. 5

    How to structure requests exception handling and check for 200 response?

  6. 6

    Node.JS - Handling incoming requests with Async functions

  7. 7

    Handling cross domain preflight AJAX OPTIONS requests with Spring MVC 4

  8. 8

    Django persistent API connections between requests

  9. 9

    Django - keeping parameters dictionary between requests

  10. 10

    Laravel sessions don't remain between requests

  11. 11

    Express Get route return error 500 : "Cast to ObjectId failed for value"

  12. 12

    Express js, GET request to the same route for the second time always pending

  13. 13

    route.js에서 Express Router 사용

  14. 14

    ui route, node, express, 404 html 파일

  15. 15

    Why React.Component is not displayed on a particular route?

  16. 16

    React Router Default Route Redirect to / home

  17. 17

    React Route Component TypeError : history is undefined

  18. 18

    Rails session store to persist search params between requests

  19. 19

    Create route between two networks in Google Cloud Compute Engine

  20. 20

    Distinguish between arguments and react events

  21. 21

    React Route로 인해 클래스 변경

  22. 22

    Route에 의한 React Router 컨디셔닝

  23. 23

    Nodejs Express에서 App Route가 작동하지 않습니다.

  24. 24

    router.route와 일치하지 않는 Express.js 4 경로

  25. 25

    Converting Express route with params from String ( '/page/:page' ) to RegExp ( /page/:page ) not working

  26. 26

    Google 인증 콜백 Express Route에서 일반 사용자 차단

  27. 27

    내 노드 변수 express 및 route 전역 화

  28. 28

    Cannot post image file from React frontend to express and MySQL

  29. 29

    Express 또는 React 및 DB 만있는 Electron

뜨겁다태그

보관