Request: BOM ๋ฌธ์ž๋กœ ์ธํ•ด JSON.parse ์‹คํŒจ

์— ๋งŒ๋“  2018๋…„ 01์›” 05์ผ  ยท  3์ฝ”๋ฉ˜ํŠธ  ยท  ์ถœ์ฒ˜: request/request

์š”์•ฝ

๋ณธ๋ฌธ์ด ๋ฒ„ํผ๋กœ ์ฑ„์›Œ์ ธ ์žˆ์„ ๋•Œ ์‘๋‹ต ๋ณธ๋ฌธ์—์„œ BOM์ด ์ œ๊ฑฐ๋˜์ง€ ์•Š์Œ

์žฌํ˜„ํ•˜๊ธฐ ์œ„ํ•œ ๊ฐ€์žฅ ๊ฐ„๋‹จํ•œ ์˜ˆ

    request({
        url: url,
        json: true,
        strictSSL: false,
    }, (error, response, data) => {
        if (error) {
            throw error;
        }

        if (response.statusCode === 200) {
            // data is string instead of json deserialized object 
        }
    })

์˜ˆ์ƒ๋˜๋Š” ๋™์ž‘

BOM ๋ฌธ์ž๊ฐ€ ์ œ๊ฑฐ๋˜๊ณ  json ์‘๋‹ต์ด ์ง๋ ฌํ™” ํ•ด์ œ๋จ

ํ˜„์žฌ ํ–‰๋™

JSON.parse๊ฐ€ ์‹คํŒจํ•˜๊ณ  ๋ฌธ์ž์—ด์ด ๋ฐ˜ํ™˜๋ฉ๋‹ˆ๋‹ค.

๊ฐ€๋Šฅํ•œ ํ•ด๊ฒฐ์ฑ…

    if (bufferLength) {
      debug('has body', self.uri.href, bufferLength)
      response.body = Buffer.concat(buffers, bufferLength)
      if (self.encoding !== null) {
        response.body = response.body.toString(self.encoding)
      }
      // `buffer` is defined in the parent scope and used in a closure it exists for the life of the Request.
      // This can lead to leaky behavior if the user retains a reference to the request object.
      buffers = []
      bufferLength = 0
    } else if (strings.length) {
      // The UTF8 BOM [0xEF,0xBB,0xBF] is converted to [0xFE,0xFF] in the JS UTC16/UCS2 representation.
      // Strip this value out when the encoding is set to 'utf8', as upstream consumers won't expect it and it breaks JSON.parse().
      if (self.encoding === 'utf8' && strings[0].length > 0 && strings[0][0] === '\uFEFF') {
        strings[0] = strings[0].substring(1)
      }
      response.body = strings.join('')
    }

์šฐ๋ฆฌ๊ฐ€ ๋ณผ ์ˆ˜ ์žˆ๋“ฏ์ด BOM char๋Š” ๋ฒ„ํผ ๋Œ€์‹  ๋ฌธ์ž์—ด์ด ์‚ฌ์šฉ๋  ๋•Œ ์ œ๊ฑฐ๋ฉ๋‹ˆ๋‹ค.
ํ•ญ์ƒ ์‘๋‹ต ๋ณธ๋ฌธ์„ ์ •๋ฆฌํ•˜๋ ค๋ฉด else if(strings.length) ์™ธ๋ถ€์—์„œ ์ฝ”๋“œ๋ฅผ ์ถ”์ถœํ•ฉ๋‹ˆ๋‹ค.

๋ฌธ๋งฅ

swashbuckle์„ ๊ธฐ๋ฐ˜์œผ๋กœ ํ•˜๋Š” ํšŒ์‚ฌ ์‚ฌ์šฉ์ž ์ง€์ • swagger์—์„œ json ์‘๋‹ต ์ฝ๊ธฐ

๋‹น์‹ ์˜ ํ™˜๊ฒฝ

| ์†Œํ”„ํŠธ์›จ์–ด | ๋ฒ„์ „
| ---------------- | -------
| ์š”์ฒญ | 2.83.0
| ๋…ธ๋“œ | 9.3.0
| npm | 5.5.1
| ์šด์˜ ์ฒด์ œ | ์œˆ๋„์šฐ 10

๊ฐ€์žฅ ์œ ์šฉํ•œ ๋Œ“๊ธ€

์š”์ฒญ ์˜ต์…˜์—์„œ encoding: 'utf8'์„ ์„ค์ •ํ•˜๋ฉด ์‘๋‹ต์ด ๊ตฌ๋ฌธ ๋ถ„์„๋ฉ๋‹ˆ๋‹ค.

๋ชจ๋“  3 ๋Œ“๊ธ€

์š”์ฒญ ์˜ต์…˜์—์„œ encoding: 'utf8'์„ ์„ค์ •ํ•˜๋ฉด ์‘๋‹ต์ด ๊ตฌ๋ฌธ ๋ถ„์„๋ฉ๋‹ˆ๋‹ค.

์ด ๋ฌธ์ œ๋Š” ์ตœ๊ทผ ํ™œ๋™์ด ์—†์—ˆ๊ธฐ ๋•Œ๋ฌธ์— ์ž๋™์œผ๋กœ ์˜ค๋ž˜๋œ ๊ฒƒ์œผ๋กœ ํ‘œ์‹œ๋˜์—ˆ์Šต๋‹ˆ๋‹ค. ๋” ์ด์ƒ ํ™œ๋™์ด ์—†์œผ๋ฉด ํ์‡„๋ฉ๋‹ˆ๋‹ค. ๊ท€ํ•˜์˜ ๊ธฐ์—ฌ์— ๊ฐ์‚ฌ๋“œ๋ฆฝ๋‹ˆ๋‹ค.

์ด ๋ฌธ์ œ๋„ ๋ณด๊ณ  ์žˆ์Šต๋‹ˆ๋‹ค. ํ•ด๊ฒฐ ๋ฐฉ๋ฒ•์„ ๊ฒŒ์‹œํ•ด ์ฃผ์…”์„œ ๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค. ํ•˜์ง€๋งŒ ๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ์—์„œ ์ด ๋ฌธ์ œ๋ฅผ ์ฒ˜๋ฆฌํ•œ๋‹ค๋ฉด ์ข‹์„ ๊ฒƒ์ž…๋‹ˆ๋‹ค.

์ด ํŽ˜์ด์ง€๊ฐ€ ๋„์›€์ด ๋˜์—ˆ๋‚˜์š”?
0 / 5 - 0 ๋“ฑ๊ธ‰