JSON无法发送到AJAX POST请求

问题描述 投票:0回答:1

我的HTML表单如下:

<form id="loginForm" name="loginForm">
   <div class="form-group">
   <input type="username" class="form-control" id="username" name="username" placeholder="Your username..." >
   </div>
   <div class="form-group">
   <input type="password" class="form-control" id="password" name="password" placeholder="Your password...">
   </div>
   <button class="btn btn-primary btn-block btn-round" id="loginButton" type="submit">Login</button>
</form>

和一个包含以下代码的Javascript文件,用于发出AJAX请求:

//credits to @lndgalante
if (typeof window !== 'undefined') {
  window.addEventListener('load', () => {
        const form = document.getElementById('loginForm');

        form.addEventListener('submit', async (event) => {
        event.preventDefault();

        const elements = event.target;
        const username = elements.username.value;
        const password = elements.password.value;
        const dataToSend = { username, password };

        try {

         console.log(JSON.stringify(dataToSend)); //To check variables are being passed correctly

         return await fetch('/login', {
            method: 'POST',
            body: JSON.stringify(dataToSend),
            headers: { 'Content-Type': 'application/json' }
          });
        } catch (error) {
          console.log(error);
        }
      });
    });
  };

以及具有相应POST路由的node.js文件:

app.post('/login', async (req, res) => {
    try {
      const username = req.body.username;
      const password = req.body.password;
      console.log(username, password, req.body); //To check variables are being passed correctly
    ...
    }
});

但是问题是,console.log(JSON.stringify(dataToSend));按预期返回{"username":"username1","password":"password1"} //or whatever the user input is,而console.log(username, password, req.body)返回undefined undefined {}

有人知道我在做什么错吗?

编辑:我正在使用const app = express();,并且我的node.js文件中有app.use(bodyParser.urlencoded({ extended: true }));

javascript html node.js ajax post
1个回答
0
投票
假设您正在使用Express.js(您应该标记问题),请确保使用express.json()(或bodyParser.json())中间件进行JSON正文解析。
© www.soinside.com 2019 - 2024. All rights reserved.