为什么发布请求返回未定义

时间:2018-09-11 17:50:23

标签: node.js

我正在从我的node.js Web应用程序向我的API发送一个发布请求。我通过发布发送到API的数据是两个字符串名称和密码。在API端,两个字符串都收到未定义的信息。我不知道为什么要这么做。

下面是我的package.json,用于显示正在使用的相关软件包:

{
  "name": "api",
  "version": "1.0.0",
  "description": "",
  "main": "api.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "nodemon -r dotenv/config api.js"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "dotenv": "^6.0.0",
    "express": "^4.16.3",
    "mongoose": "^5.2.14"
  },
  "devDependencies": {
    "nodemon": "^1.18.4"
  }
}

这是用户在其中输入数据的HTML:

<!DOCTYPE html>
<html>
    <head>
        <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" integrity="sha384-WskhaSGFgHYWDcbwN70/dfYBj47jz9qbsMId/iRN3ewGhXQFZCSftd1LZCfmhktB" crossorigin="anonymous">
        <meta charset="utf-8" />
        <meta name="description" content="A frontend dashboard for the
        TrackMe application" />
        <meta name="author" content="name" />
        <meta name="viewport" content="width=device-width, initialscale=1.0">
        <link rel="stylesheet" href="style.css" />
        <title>TrackMe</title>
    </head>

    <body>
        <div id="navbar"></div>
        <div class="container">
                <h1>Registration</h1>

            <div class="form-group">
                    <label for="user">Username</label>
                    <input type="text" placeholder="Enter Username" class="form-control" id="username" />
                    <div id='messageError' ></div>
            </div>

            <div id='userError'></div>

            <div class="form-group">
                <label for="password">Password</label>
                <input type="text" placeholder="Enter Password" class="form-control" id="password" />
            </div>

            <div class="form-group">
                    <label for="confirm-password"> Confirm Password</label>
                    <input type="text" placeholder="Enter Password" class="form-control" id="confirm-password" />
            </div>

            <div id='passwordError'></div>

            <button class="btn btn-primary" id='register-account' href="/login.html">Register</button>
            <br>
            <br>

            <p>Already have an account? Sign in <a href="/login">here</a>.</p>
        </div>
        <div id="footer"></div> 

        <script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
        <script src="app.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script>
        <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js" integrity="sha384-smHYKdLADwkXOn1EmN1qk/HfnUcbVRZyYmZ4qpPea6sjB/pTJ0euyQp0Mk8ck+5T" crossorigin="anonymous"></script>
    </body>
</html>

这是我的app.js发送数据的代码:

$('#register-account').on('click', function() { 
    const name = $('#username').val();
    const password = $('#password').val();
    const passwordConfirm = $('#confirm-password').val();
    const body = {
        name,
        password
    }
    //Checking password credentials match
    const confirmedPassword = password == passwordConfirm
    if (!confirmedPassword){
        $('#passwordError').append('<p class="alert alert-danger" style="font-style: italic"> ERROR: Password does not match </p>')
    }
    else 
        $.post(`${API_URL}/register`, body)
            .then((response) =>{
                console.log(response);
                if(response.success){
                location.href = "/login"
                // localStorage.setItem('name', name);
                // localStorage.setItem('isAdmin', response.isAdmin);
                }
            })
        .catch(error => {
            console.log(`Error: ${error}`);
        }
)});

正在通过点击处理程序检索名称和密码变量。

这是api端的代码:

app.post('/api/register', (req, res) => {
  const {name, password, isAdmin} = req.body;
  console.log('req.body data from register post endpoint:')
  console.log(req.body);
  User.findOne({ 'name': name }, function (err, user) {
    if(err!=null){
      console.log('Err section api/register');
      return res.json({
        success: false,
        message: err
      });
    }
    else{
      if(user!=null){
        console.log('user !=null api/register');
        // console.log(name);
        // console.log(password);
        return res.json({
          success: false,
          message: "user already exists"
        });
      }
      else{
        console.log(req.body);
        console.log("create new user");
        const newUser = new User({
          name,
          password,
          isAdmin
        });

        newUser.save(err => {
          return err
          ? res.send(err)
          : res.json({
            success: true,
            message: 'Created new user'
          });
        });
      }
    }
  });
});

2 个答案:

答案 0 :(得分:1)

我想您正在使用Express框架来设置服务器。也许您尚未将其配置为将正文反序列化为JSON? 这是一个有关如何实现此目标的问题和很好的答案:How do I consume the JSON POST data in an Express application

400px打印什么?

答案 1 :(得分:0)

因此,在进行了一些研究之后,我发现我的api.js文件中没有包含正确的body.parser。

//SOURCE OF THE ERROR WITH THE POST REQUEST
app.use(bodyParser.urlencoded({
  extended: true
}));

我在顶部附近添加了这段代码,现在问题已解决。 Req.body正在接收所有信息,并且该应用程序现在正在运行。