文本区域Javascript中的撇号



我创建了一个公司论坛。用户可以创建帖子来共享信息。为了做到这一点,他们现在完成了一个带有基本文本区域的表单。我的问题是,当他们写一个带有撇号的单词时,代码会将撇号解释为单引号,从而产生异常。我向您展示下面的代码和示例。

Html:

<!DOCTYPE html>
<html lang="fr">
<head>
<meta charset="utf-8">
</head>
<body>
<div id="admin">
<div v-if="seenNews" id="news">
<div class="form">
<h4>Create a post</h4>
<form class="newPost" action="/newPost" method="POST">
<label id="titleLabel" for="titleInput">Title : </label>
<input type="text" id="titleInput" name="titleInput" required>
<label id="contentLabel" for="contentInput">Content : </label>
<textarea id="contentInput" name="contentInput" cols="40" rows="5" required></textarea>
<button type="submit">Create</button>
</form>
</div>
</div>
</div>
</body>
</html>

后端javascript:

app.js

const Server = require('./server/Server');
const express = require('express');
const DAO = require('./server/DAO');
const server = new Server();
server.start();
const dao = new DAO();
dao.connect();
server.app.post("/newPost", function(req, res) {
try {
dao.newPost(req.body.titleInput, req.body.contentInput).then(value => {
res.redirect('/Admin');
})
} catch (e) {
console.log(e);
}
})

DAO.js

const sql = require('mssql');
class DAO {
constructor() {
this.sqlConfig = {
user: 'username',
password: 'password',
server: 'SERVER',
port:port,
database: 'DB',
options: {
enableArithAbort: false,
encrypt:false
}
}
}
async newPost(title, content) {
try {
let req = 'INSERT INTO DB.dbo.[Table] (title, content) VALUES (''+title+'',''+content+'')';
console.log(req);
await sql.query(req).then(value => {
return true;
});
} catch (e) {
console.log(e);
return false;
}
}
}

举个例子,如果一个用户创建了一个包含以下内容的帖子:Ms. Smith's keys are at the reception desk,我会在控制台中有这个:

RequestError: Unclosed quotation mark after the character string ')'.

也许如果我创建一个函数来查找并编码字符,它可以修复它,但我不知道如何做到这一点。

我最后使用JS函数replace((将字符串中的简单引号替换为两个简单引号。''相当于sql server中的js'

'INSERT INTO PROFACE.dbo.[Posts] (title, content) VALUES (''+title.replace(/'/gi,"''")+'',''+content.replace(/'/gi,"''")+'')'

最新更新