JSON没有通过AJAX POST请求发送 [英] JSON isn't getting sent through to AJAX POST request

查看:92
本文介绍了JSON没有通过AJAX POST请求发送的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的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 }));.

解决方案

您必须使用正文解析器,否则您的NodeJS应用程序将不知道如何解释在请求正文中收到的字符串.

npm install --save body-parser

var bodyParser = require('body-parser')
app.use( bodyParser.json() );       // to support JSON-encoded bodies
app.use(bodyParser.urlencoded({     // to support URL-encoded bodies
  extended: true
})); 

app.use(express.json());
app.use(express.urlencoded());
app.use(express.multipart());

因此您的代码将正确运行.

此处有更多详细信息:如何检索POST查询参数?

I have a HTML form as follows:

<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>

and a Javascript file containing the following code to make an AJAX request:

//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);
        }
      });
    });
  };

and a node.js file with the corresponding POST route:

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

But the problem is, console.log(JSON.stringify(dataToSend)); returns {"username":"username1","password":"password1"} //or whatever the user input is as expected, whereas console.log(username, password, req.body) returns undefined undefined {}.

Does anyone know what I'm doing wrong?

Edit: I am using const app = express(); and I have app.use(bodyParser.urlencoded({ extended: true })); in my node.js file.

解决方案

You must use a body parser, otherwise your NodeJS application will not know how to interpret your string received in the request body.

npm install --save body-parser

and

var bodyParser = require('body-parser')
app.use( bodyParser.json() );       // to support JSON-encoded bodies
app.use(bodyParser.urlencoded({     // to support URL-encoded bodies
  extended: true
})); 

or

app.use(express.json());
app.use(express.urlencoded());
app.use(express.multipart());

So your code will run propperly.

More details here: How to retrieve POST query parameters?

这篇关于JSON没有通过AJAX POST请求发送的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆