简体   繁体   English

结合使用jQuery ajax和node.js发送POST请求

[英]Using jQuery ajax with node.js to send POST request

I have the following in myserver/index.js (which I run with node): 我的myserver/index.js有以下内容(与节点一起运行):

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 <script> section of my myserver/public/signup/index.html file 我的myserver/public/signup/index.html文件的<script>部分中包含以下内容

function submit() {
  $.ajax({
    url: "submit",
    type: "POST",
    contentType: "application/xml",
    data: '<?xml version="1.0"?><user>John Smith</user>',
    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: {}". 调用commit()时,弹出警报,提示“错误:无效的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. req的控制台转储中,我看到该body确实为空,但是进一步检查显示它已经收到了所有其他数据。 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. 我是Ajax,jQuery和Node.js的新手,所以我不知道自己在做什么错。 I feel like it's something little I'm missing. 我觉得这是我缺少的东西。

Thanks. 谢谢。

Try this: 尝试这个:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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