3

我的 REST 服务如下:

const
  express = require('express'),
  app = express();
  
  ...
  
 app.get('/turkish-escape/:id', function(req, res) {
  console.log("converting turkish special characters:");
  console.log("\u011f \u011e \u0131 \u0130 \u00f6 \u00d6 \u00fc \u00dc \u015f \u015e \u00e7 \u00c7");
  let char = req.params.id;
  
 .....//DO stuff

当我尝试在浏览器中获取服务时,我没有收到任何错误: http://localhost:8081/turkish-escape/ğ/

当我尝试使用我的 REST 客户端获得结果时,我遇到了一些土耳其特殊字符的问题。

客户端代码:

let currentChar = text[i];
  let
    request = require('request'),
    options = {
      method: 'GET',
      url: 'http://localhost:8081/turkish-escape/' + currentChar + "/"
    };
    request(options, function(err, res, body) {
      if(err) {
        throw Error(err);
      } else {
        body = JSON.parse(body);
        console.log(body.convertedChar);
        newText += body.convertedChar;
      }
    });

当我用 'ü' 调用客户端时,它工作正常,但如果我用 'ğ' 调用它,它会崩溃。这是调用和堆栈跟踪:

./turkishTextConverter.js ğ
/pathtofile/turkishTextConverter.js:25
    throw Error(err);
    ^

Error: Error: socket hang up
at Request._callback (/pathtofile/turkishTextConverter.js:25:15)
at self.callback (/pathtofile/node_modules/request/request.js:188:22)
at emitOne (events.js:96:13)
at Request.emit (events.js:191:7)
at Request.onRequestError (/pathtofile/node_modules/request/request.js:884:8)
at emitOne (events.js:96:13)
at ClientRequest.emit (events.js:191:7)
at Socket.socketOnEnd (_http_client.js:394:9)
at emitNone (events.js:91:20)
at Socket.emit (events.js:188:7)

正如您从堆栈中看到的那样,它甚至从未到达 REST 服务的第一个 console.log 语句

4

1 回答 1

1

解决方案是将 URL 编码为 URI:

...
url: 'http://localhost:8081/turkish-escape/' + currentChar + "/"
...

...
url: encodeURI('http://localhost:8081/turkish-escape/' + currentChar + '/')
...

现在客户端不会再崩溃了

于 2017-05-07T17:24:47.457 回答