[Resolved] UnsupportedMediaTypeError: unsupported charset “SHIFT_JIS”

  • 2 Tháng Mười Một, 2022

Khi làm việc với các dự án Nhật sử dụng cổng thanh toán sbpayment, lúc thanh toán thành công, cổng thanh toán này sẽ call đến endpoint xử lý dữ liệu bên mình được set ở pagecon_url theo method POST kèm header

Content-type: "application/x-www-form-urlencoded; charset=Shift_JIS"
Code language: JavaScript (javascript)

Bắt buộc mình phải sử dụng cách bên dưới để lấy được dữ liệu:

const express = require('express') const app = express() const bodyParser = require('body-parser') app.use(bodyParser.urlencoded({ extended: true })) app.post('/callback_paypay', async (req, res) => { console.log(req.body) });
Code language: JavaScript (javascript)

Nghĩ thầm vậy oke rồi chạy thôi chứ suy nghĩ gì nữa :))) nhưng không, thằng bodyParser nó lại không support encoding Shift_JIS nên văng lỗi

UnsupportedMediaTypeError: unsupported charset “SHIFT_JIS”
Code language: HTTP (http)

Thử check lib nó xem sao :)))) chỉ hỗ trợ utf-8

//File body-parser/lib/types/urlencoded.js // assert charset var charset = getCharset(req) || 'utf-8' if (charset !== 'utf-8') { debug('invalid charset') next(createError(415, 'unsupported charset "' + charset.toUpperCase() + '"', { charset: charset, type: 'charset.unsupported' })) return }
Code language: JavaScript (javascript)

Cách giải quyết:

const express = require('express') const app = express() const qs = require('qs') const contentType = require('content-type') const getBody = require('raw-body') const port = 2033 app.use(function (req, res, next) { getBody(req, { length: req.headers['content-length'], encoding: contentType.parse(req).parameters.charset }, function (err, result) { if (err) return next(err) req.body = qs.parse(result) next() }) }) app.post('/callback_paypay', async (req, res) => { console.log(req.body) }); app.listen(port, () => console.log(`Example app listening at http://localhost:${port}`))
Code language: JavaScript (javascript)

0
Rất thích suy nghĩ của bạn, hãy bình luận.x