【问题标题】:Node requestify fails when body includes special chars当正文包含特殊字符时,节点请求失败
【发布时间】:2016-10-07 07:11:31
【问题描述】:

我正在使用 node.js 和一个名为 requestify 的库。 代码如下所示:

console.log('body');
console.log(body);
return new Promise(function (f, r) {
        requestify.request(myurl, {
            method: 'POST',
            body : body,
            headers : {
                "Content-Type" : "application/json; charset=utf-8"
            }
        })
            .then(function (response) {
                f({messge : "Success"});
            }, function (err) {
                console.log(err);
                err.code == 405 ? r(err.body) : r({ success: false, message: err });
            });
    });

当请求包含特殊字符(在本例中为瑞典字符)时,它会引发错误。

发送完全相同的请求,没有瑞典字符,请求成功。

我真的无法访问正在处理请求的服务器,这就是它难以调试的原因。 但是我在发送请求之前打印了正文,我看不到其中有任何奇怪的东西。 以下是 2 个不同的 body-requests:

//失败

{ eventType: 'createUser',
eventId: '1e2ca3b4-0f6b-4ed9-ae79-2e112c8d693c',
version: '0.1',
date: 2016-10-07T06:42:26.209Z,
attributes: 
 { userName: 'akeandersson@gmail.se',
 email: 'akeandersson@gmail.se',
 firstName: 'Åke',
 lastName: 'Andresson',
 phoneNumber: '1',
 identifier: '198509120328',
 assignment: 'se.me',
 role: [ 'se.me.role.user' ] },
 metadata: {} }

//成功

{ eventType: 'createUser',
eventId: '1e2ca3b4-0f6b-4ed9-ae79-2e112c8d693c',
version: '0.1',
date: 2016-10-07T06:44:09.857Z,
attributes: 
{ userName: 'akeandersson212@gmail.se',
email: 'akeandersson212@gmail.se',
firstName: 'Ake',
lastName: 'Andresson',
phoneNumber: '9',
identifier: '196606095823',
assignment: 'se.me',
role: [ 'se.me.role.user' ] },
metadata: {} }

我还在标题的内容类型中添加了“; charset=utf-8”(根据 requestify 文档,默认情况下它已经是 utf-8)。 但还是一样的结果。知道如何调试吗?

这是请求失败时服务器返回的内容:

{
code: 400,
headers: 
{ connection: 'close',
'content-type': 'text/plain',
'content-length': '244',
date: 'Fri, 07 Oct 2016 06:42:27 GMT' },
body: 'Unexpected end-of-input: expected close marker for OBJECT (from  [Source: ServletInputStreamImpl@75eb88e4; line: 1, column: 0])\n at [Source: ServletInputStreamImpl@75eb88e4; line: 1, column: 767]' }

【问题讨论】:

  • 你有哪个版本的requestify
  • “请求”:“^0.1.17”
  • 这些响应都不是有效的 JSON,所以我很惊讶它们都起作用了。
  • 您可以尝试使用不同的编码上传数据(使用 cURL 之类的编码可能会更容易),以查看服务器是否特别存在 UTF-8 问题。

标签: javascript json node.js http


【解决方案1】:

我猜,您需要将您的 requestify 模块上传到最新版本。我使用version 0.2.3,它不会给我带来任何错误。

假设您在尝试读取norwegian(或)swedish 字符时遇到错误,我尝试读取其中包含norwegian 字符的网站,并且使用以下代码,我可以将其输出到控制台而不会出现任何错误。 swedish 页面也一样。我正在使用0.2.3 版本(这是最新版本)。我也没有将编码设置为UTF-8

var requestify = require('requestify'); 

requestify.get('http://www.norwegian4people.com/lesson.php?id=41').then(function(response) {
    // Get the response body 
    console.log(response.getBody());
});

希望这会有所帮助!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-08-06
    • 2017-07-16
    • 2014-08-02
    • 1970-01-01
    • 2012-02-26
    • 2020-04-26
    • 2021-01-08
    • 2012-11-20
    相关资源
    最近更新 更多