综合技术

Using jQuery ajax with node.js to send POST request

微信扫一扫,分享到朋友圈

Using jQuery ajax with node.js to send POST request
0

I have the following in myserver/index.js
(which I run with node):

server.configure(function() {
  server.use(express.methodOverride());
  server.use(express.bodyParser());
  server.use(server.router);
  server.use(express.static(__dirname + '/public'));
  server.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
});

server.post('/signup/submit', function(req, res) {
  console.log(req);
  res.send(req.body);
});

server.listen(process.env.PORT || 12345, function() {
  console.log('Server listening');
});

I have the following in the
section of my myserver/public/signup/index.html
file

function submit() {
  $.ajax({
    url: "submit",
    type: "POST",
    contentType: "application/xml",
    data: 'John Smith',
    dataType: "xml",
    success: function(data, textStatus, jqXHR) { alert(data); },
    error: function(jqXHR, textStatus, errorThrown) { alert(errorThrown); }
});

When submit() gets called, an alert pops up saying “Error: Invalid XML: {}”. From the console dump of req
, I see that body
is indeed empty, but further examination shows that it has received all the other data. Here is the header:

headers: 
{ host: 'localhost:12345',
  connection: 'keep-alive',
  'content-length': '44',
  origin: 'http://localhost:12345',
  'x-requested-with': 'XMLHttpRequest',
  'user-agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.11 (KHTML, like Gecko) Chrome/20.0.1132.57 Safari/536.11',
  'content-type': 'application/xml',
  accept: 'application/xml, text/xml, */*; q=0.01',
  referer: 'http://localhost:12345/signup/',
  'accept-encoding': 'gzip,deflate,sdch',
  'accept-language': 'en-US,en;q=0.8',
  'accept-charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.3' }

I’m new to Ajax, jQuery, and Node.js
, so I don’t know what I’m doing wrong. I feel like it’s something little I’m missing.

Thanks.

Problem courtesy of: Nick

Solution

Try this:

$.ajax({
    url: "submit",
    type: "POST",
    contentType: "application/xml",
    data: "John Smith", // remove <?xml ...
    dataType: "xml",
    success: function(data, textStatus, jqXHR) { alert(data); },
    error: function(jqXHR, textStatus, errorThrown) { alert(errorThrown); }
});

Solution courtesy of: wanovak

阅读原文...


Node.js Recipes

习近平贺信数博会引热烈反响;阿里云将为“天眼”提供计算存储解...

上一篇

智东西早报:传蔚来提交IPO申请 马化腾入选全球最佳CEO

下一篇

您也可能喜欢

评论已经被关闭。

插入图片
Using jQuery ajax with node.js to send POST request

长按储存图像,分享给朋友