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

时间:2012-07-24 22:32:48

标签: jquery ajax node.js post xmlhttprequest

我在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');
});

我在<script>文件的myserver/public/signup/index.html部分中有以下内容

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

当调用submit()时,会弹出一条警告“错误:无效的XML:{}”。在req的控制台转储中,我看到body确实是空的,但进一步检查显示它已收到所有其他数据。这是标题:

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

我是Ajax,jQuery和Node.js的新手,所以我不知道我做错了什么。我觉得这是我缺少的一点点。

感谢。

1 个答案:

答案 0 :(得分:1)

试试这个:

$.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); }
});
相关问题