简体   繁体   English

如何发送Ajax POST请求

[英]How to send an Ajax POST request

I'm using this code to send a POST to my node API to generate a PDF, my node console gives me these errors: 我正在使用此代码将POST发送到我的节点API以生成PDF,我的节点控制台给了我这些错误:

$('#renderPDF').click(function(){
      var request = $.ajax({
        type: "POST",
        url: 'http://localhost:8080/api/v1/generate',
        data: {doc:"<h1>test 123</h1>"},
      });
      request.done(function(data){
        console.log(data);
      });
});

info: TypeError: null is not an object (evaluating 'child.transform') info: info: phantomjs://code/shim.js:157 in transform info: 信息:TypeError:空值不是对象(正在评估'child.transform')信息:信息:phantomjs://code/shim.js:157转换信息:
phantomjs://code/shim.js:138 in read phantomjs://code/shim.js:138已读取

When I send a POST (with the Postman tool), the PDF is rendered and everything works. 当我发送POST(使用Postman工具)时,将呈现PDF,并且一切正常。

localhost:8080/api/v1/generate?doc=<h1>testing 123</h1>

What am I doing wrong on my POST request? 我在POST请求上做错了什么?

I think your problem is that you are sending the doc parameter as a POST parameter, when it looks like its a querystring, try: 我认为您的问题是您正在将doc参数作为POST参数发送,当它看起来像是查询字符串时,请尝试:

$('#renderPDF').click(function(){
  var request = $.ajax({
    type: "POST",
    url: 'http://localhost:8080/api/v1/generate?doc=<h1>testing 123</h1>',
  });
  request.done(function(data){
    console.log(data);
  });
});

Hope it solves your problem. 希望它能解决您的问题。

EDIT: more info on this. 编辑:对此的更多信息。 You may be sending the request (from postman) as a POST request, but the values sent are not actually POST parameters, they are querystrings ("GET" parameters if you will). 您可能以POST请求的形式发送请求(来自邮递员),但是发送的值实际上不是POST参数,它们是查询字符串(如果愿意,则为“ GET”参数)。

Probably you need/can achieve it easier with formData 可能您需要/可以使用formData轻松实现它

eg 例如

data = new FormData();
data.append( 'doc', "<h1>test 123</h1>" );

$.ajax({
    url: 'http://localhost:8080/api/v1/generate',
    data: data,
    processData: false,
    type: 'POST',
    success: function ( data ) {
        alert( data );
    }
});

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

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