Приложение Nodejs Express показывает странные символы для хинди, опрашивая базу данных Sqlite - PullRequest
0 голосов
/ 14 июня 2019

API сделан с использованием Nodejs Express.Этот API хинди является живым, показывая странный символ для языка хинди.Это Английская версия отлично отображает результаты на английском языке.Ниже приведен код для хинди API:

app.get("/api/find/hindi/:find",function(request, response)
{
    let db = new sqlite3.Database("./quranDb.db",(err) => {
        if (err){
        console.log("Not connected to sqlite")
        }
        else{
            console.log("Connected to sqlite")
        }
    });

    let sql = `SELECT Surat_ID, Ayat_ID, Surat_Name, Hindi FROM QuranTest`;

db.all(sql, [], (err, rows) => {
  if (err) {
    throw err;
  }
  rows.forEach((row) => {
    ayats.push(JSON.stringify({Translation: row.Hindi,SuratName: row.Surat_Name,SuratID: row.Surat_ID,AyatNo: row.Ayat_ID}));
  });
  //console.log(ayats);
  Translation="";
  Surat_No="";
  Surah_Name="";
  Ayat_No="";
  try {
  ayats.forEach(function(element) {
    if (element.toLowerCase().includes(request.params.find.toLowerCase())===true)
    {
      counting++;
      element=JSON.parse(element);
      Surah_Name = element.SuratName;
      Ayat_No = element.AyatNo;
      Surah_No = element.SuratID
      Translation = "In Surah "+ element.SuratName+", Ayat Number: "+element.AyatNo+", Quran says: "+ element.Translation;
      const tempObj={
        Surah_No,
        Surah_Name,
        Ayat_No,
        Translation
      }
      parentObj[`result_${counting}`]=tempObj
    }
  if (counting===10){
    throw BreakException
  }

})
  } catch(e) {
    if (e!==BreakException) throw e
  }
  if (counting ===0){
  response.write(JSON.stringify({"speech":"No results found"}))
    }  
  else{
    response.write(JSON.stringify(parentObj))
  }
  response.send();
  counting = 0;
  parentObj={};
});


empty();
function empty() {
    ayats.length = 0;
}

db.close((err) => {
    if (err) {
      return console.error(err.message);
    }
    console.log('Close the database connection.');
  });

})

Хинди API

Как видно, значение поля translation является бредом.Это должно быть в формате хинди.База данных SQL не имеет никаких проблем.Это показывает идеальный хинди.enter image description here

Английский API enter image description here

Я также пытался

...

}


  else{
    response.write(JSON.stringify(parentObj))
  }
  response.writeHead(200, {"Content-Type": "text/html; charset=utf-8"});
  response.send();
  counting = 0;
...

но он останавливает выполнение хинди апи.Браузер возвращает ошибку, чтобы обновить страницу и т. Д.

1 Ответ

0 голосов
/ 14 июня 2019

Я правильно понял. Моя ошибка заключалась в том, что недостаточно только указать заголовок о кодировке utf-8. response.write(JSON.stringify(parentObj),"utf-8") также необходимо знать, какой кодировке должно следовать тело.

app.get("/api/find/hindi/:find",function(request, response)
{
    let db = new sqlite3.Database("./quranDb.db",(err) => {
        if (err){
        console.log("Not connected to sqlite")
        }
        else{
            console.log("Connected to sqlite")
        }
    });
    response.writeHead(200, {"Content-Type": "text/html; charset=utf-8"}); 
    let sql = `SELECT Surat_ID, Ayat_ID, Surat_Name, Hindi FROM QuranTest`;

db.all(sql, [], (err, rows) => {
  if (err) {
    throw err;
  }
  rows.forEach((row) => {
    ayats.push(JSON.stringify({Translation: row.Hindi,SuratName: row.Surat_Name,SuratID: row.Surat_ID,AyatNo: row.Ayat_ID}));
  });
  //console.log(ayats);
  Translation="";
  Surat_No="";
  Surah_Name="";
  Ayat_No="";
  try {
  ayats.forEach(function(element) {
    if (element.toLowerCase().includes(request.params.find.toLowerCase())===true)
    {
      counting++;
      element=JSON.parse(element);
      Surah_Name = element.SuratName;
      Ayat_No = element.AyatNo;
      Surah_No = element.SuratID
      Translation = "In Surah "+ element.SuratName+", Ayat Number: "+element.AyatNo+", Quran says: "+ element.Translation;
      const tempObj={
        Surah_No,
        Surah_Name,
        Ayat_No,
        Translation
      }
      parentObj[`result_${counting}`]=tempObj
    }
  if (counting===10){
    throw BreakException
  }

})
  } catch(e) {
    if (e!==BreakException) throw e
  }
  if (counting ===0){
  response.write(JSON.stringify({"speech":"No results found"}),"utf-8")
    }  
  else{
    response.write(JSON.stringify(parentObj),"utf-8")
  }

  response.send();
  counting = 0;
  parentObj={};
});


empty();
function empty() {
    ayats.length = 0;
}

db.close((err) => {
    if (err) {
      return console.error(err.message);
    }
    console.log('Close the database connection.');
  });

})

enter image description here

...