简体   繁体   English

处理 React 和 Express 之间的路由请求

[英]Handling route requests between React and Express

I am creating an app with login and registration functionality with React and Express.我正在使用 React 和 Express 创建一个具有登录和注册功能的应用程序。 I am using Formik to handle the form data as well as to post it:我正在使用 Formik 处理表单数据以及发布它:

> 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:然后将其发送到 express 应用程序,并通过以下路由:

> 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) 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.这是我可以将表单数据导入 express 的唯一方法,如果我不包含分号并使用 req.params 调用这些值,我会收到“404 未找到错误”,因为 3 个值是空的。 If I try and access them via req.body they still appear to be empty.如果我尝试通过 req.body 访问它们,它们仍然显示为空。 I have tried to JSON.stringify them and I am using body-parser in the express app.我试图对它们进行 JSON.stringify,并且我在 express 应用程序中使用了 body-parser。 My question is how can I access these 3 values(username, email, password) with req.body?我的问题是如何使用 req.body 访问这 3 个值(用户名、电子邮件、密码)? 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如果我想从我的浏览器访问这条路线,还有一种特定的方式我应该格式化它们,例如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.我已经做了 mysql 查询来检查这个并在 express 中更新一个变量我只需要然后发送响应,也许该变量的值将告诉 react 转到索引页面。 However res.send(variable) does not seem to be sending the variable to react and the login form stays stagnant after it is submitted.然而 res.send(variable) 似乎并没有发送变量来做出反应,并且登录表单在提交后保持停滞。

To access the body use method:"POST" rather than GET.要访问正文,请使用method:"POST"而不是 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"})
       })
    ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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