简体   繁体   中英

AJAX Error: 400 Bad Request

I am using mithril.js to connect with my node back-end. I was following documentation adding in the AJAX request and there is little documentation on mithril elsewhere.

Anyway, Error:

mithril.js:2130 POST http://localhost:3000/api/stocks 400 (Bad Request)
ta @ mithril.js:2130
ua @ mithril.js:2138
k.request @ mithril.js:2227
vm.add @ app.js:24
(anonymous) @ mithril.js:1246
mithril.js:2197 Uncaught SyntaxError: Unexpected token < in JSON at position 0
    at parse (<anonymous>)
    at Object.a.onload.a.onerror (mithril.js:2197)
    at XMLHttpRequest.d.onreadystatechange (mithril.js:2102)
a.onload.a.onerror @ mithril.js:2197
d.onreadystatechange @ mithril.js:2102

mithril.js

vm.add = function() {
            var data = vm.symbol();
            if (vm.symbol()) {
                m.request({method: 'POST',
                            url: '/api/stocks',
                            data: data,
                            unwrapSuccess: function(response) {
                              return response.data;
                            },
                            unwrapError: function(response) {
                              return console.log(response.error);
                              }
                            });
                vm.list.push(new app.Stock({symbol: vm.symbol()}));
                vm.symbol("");
            }
        };

routes/index.js (node)

router.post('/api/stocks', function(req, res) {
  Stocks.create({
    stock: req.body.text, //stocks
    date_added: new Date(), //Date
  }, function (err, stocks) {
    if (err) {
      res.send(err);
    } else {
      Stocks.find(function(err, stocks) {
        if (err) {
          res.send(err);
        } else {
          res.json(stocks);
        }
      });
    };
  });
});

Any ideas?

Thank you.

The issue was caused because Mithril automatically assumes that the data would be in JSON. I was trying to send plain text. Mithril has a method for this called "deserialize".

Deserialize didn't work so I looked again and express didn't like the fact that there wasn't JSON so I converted the data to JSON and then the POST request worked fine.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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