Problems making http-post requests with German umlauts (ä ö ü) or special chars (ß) with Node.js

若如初见. 提交于 2020-01-06 02:52:06

问题


TLDR; solved, see comments below :)

I am really getting nuts with this: I want to post JSON to the Redmine API to send time entries imported via CSV files. Everything works well, until I try to send strings with German umlauts (ä ü ö) or special chars (ß).

I am using the request package with the following code:

var options = {
    url: self.getHost() + path,
    headers: {
        'Content-Type': 'application/json; charset=utf-8'
    },
    method: method
};

options.headers[self.getApiKeyHeader()] = self.getApiKey();

if (method !== HttpMethods.Get) {

    params.time_entry.comments = 'äöüß';

    options.body = JSON.stringify(params);
    options.headers['Content-Length'] = options.body.length;
}

And send it like this:

request(options, function (error, response) {

    if (response.statusCode === 201) {

        console.log('Success');
    } 
    else {

        console.log('Error: ' + response.statusCode);
    }
});

I always get an HTTP500 Error with server logs saying "Invalid byte sequence in UTF-8". I get the same error when I try to post the JSON via Postman. As my coworkers have no problems with Ruby and PHP script, I guess I got something terribly wrong in my script. Also tried the following alternatives for setting the options.body content:

options.body = new Buffer(JSON.stringify(params), encoding='utf8');
options.body = new Buffer(JSON.stringify(params, 'ascii').toString('utf8');

With both also not working.

I am using https://www.npmjs.com/package/request for the requests.

What am I doing wrong?

来源:https://stackoverflow.com/questions/27807252/problems-making-http-post-requests-with-german-umlauts-%c3%a4-%c3%b6-%c3%bc-or-special-chars

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!