【问题标题】:How to response json TIS-620 to UTF-8 in Node js + Express (API)如何在 Node js + Express (API) 中将 json TIS-620 响应为 UTF-8
【发布时间】:2018-09-03 09:26:13
【问题描述】:

我无法使用 tis-620 以我的语言获取数据

[MySQL 结构]

CREATE TABLE `foo` (
  `id` int(11) NOT NULL,
  `name` varchar(20) DEFAULT NULL,
  `address` varchar(60) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=tis620

[MySQL 数据]

| id |   name   |    address    |
--------------------------------|
|  1 | ทดสอบ   | 6/12 บ้านแสนดี  |

[NodeJS函数]

function getAllFoo() {
    return new Promise((resolve, reject) => {
        try {

            // Retrieving
            db.query("SELECT * FROM foo", (err, rows, fields) => {
                if(err) { throw err }
                resolve(rows)
            })

        } catch (error) {
            reject(error)
        }
    })
}

[NodeJS API]

const Foo = require('./foo')

app.get('/getFoo', (req, res) => {

    Foo.getAllFoo().then((rows) => {

         res.header("Content-Type", "application/json; charset=utf-8")
         res.status(200).json(rows)

     }).catch((err) => {
         throw err
     })

    res.status(200).json(rows);
})

然后,我尝试请求此端点/getFoo,但响应数据是:��ҹ������

[响应json数据]

[
  {
    "id" : 1,
    "name" : "��ҹ.������",
    "address" : "��ҹ������ �.� �.������"
  }
]

我将在我的 PHP 项目中使用这个 JSON 结果

【问题讨论】:

  • 可持续的解决方案是在任何地方使用 UTF-8。

标签: json node.js api express utf-8


【解决方案1】:

解决方案:

[MySQL 连接] - 在 mysql 连接中添加 charset 到 tis620 并在连接数据库时添加 "SET NAMES UTF8"

var mysql      = require('mysql');

var connection = mysql.createConnection({

  host     : 'example.org',
  user     : 'bob',
  password : 'secret'
  charset  : 'tis620'

})

connection.connect(function(err) {

  if (!err) {

    connection.query("SET NAMES UTF8")

    console.log('connected as id ' + connection.threadId);

  } else {     

    console.error('error connecting: ' + err.stack);        

  }

});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-09-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-22
    • 2016-03-13
    相关资源
    最近更新 更多