NodeJS使用请求模块获取包含中文的URL(NodeJS use the request module get a url that contains chinese)

我想使用看起来像https://example.com/book/search/q?={bookName}的RESTful API。 我使用节点模块request模拟POST请求。 当bookName是完整的英语时,它运作良好。 但是当bookName包含中文时,它就不起作用了。 这是我的代码:

request({ uri: 'https://example.com/book/search?q=' + bookName, method: 'GET' }, function (error, response, body) { if (!error && response.statusCode == 200) Do something ... });

提前致谢。

I want to use a RESTful API that looks like https://example.com/book/search/q?={bookName}. I use the node module request analog POST request. When the bookName is full english, it works well. But when the bookName contains chinese, it dosen't work. Here is my code:

request({ uri: 'https://example.com/book/search?q=' + bookName, method: 'GET' }, function (error, response, body) { if (!error && response.statusCode == 200) Do something ... });

Thanks in advance.

最满意答案

你必须对名称进行编码。 使用

uri: 'https://example.com/book/search?q=' + encodeURIComponent(bookName),

You have to encode the name. Use

uri: 'https://example.com/book/search?q=' + encodeURIComponent(bookName),NodeJS使用请求模块获取包含中文的URL(NodeJS use the request module get a url that contains chinese)

我想使用看起来像https://example.com/book/search/q?={bookName}的RESTful API。 我使用节点模块request模拟POST请求。 当bookName是完整的英语时,它运作良好。 但是当bookName包含中文时,它就不起作用了。 这是我的代码:

request({ uri: 'https://example.com/book/search?q=' + bookName, method: 'GET' }, function (error, response, body) { if (!error && response.statusCode == 200) Do something ... });

提前致谢。

I want to use a RESTful API that looks like https://example.com/book/search/q?={bookName}. I use the node module request analog POST request. When the bookName is full english, it works well. But when the bookName contains chinese, it dosen't work. Here is my code:

request({ uri: 'https://example.com/book/search?q=' + bookName, method: 'GET' }, function (error, response, body) { if (!error && response.statusCode == 200) Do something ... });

Thanks in advance.

最满意答案

你必须对名称进行编码。 使用

uri: 'https://example.com/book/search?q=' + encodeURIComponent(bookName),

You have to encode the name. Use

uri: 'https://example.com/book/search?q=' + encodeURIComponent(bookName),