【发布时间】:2025-11-23 09:45:01
【问题描述】:
我似乎无法理解这一点。我有一个正确设置的连接,并且能够从前端从我的数据库中获取数据,但是我相信某些语法有问题。我将用户输入存储在“searchTerm”中,我正在尝试使用占位符运行查询?。
我遇到问题的代码是
app.get('/api/get', (req, res)=> {
const searchTerm = req.body.searchTerm;
const sqlSelect = "SELECT * FROM questions WHERE MATCH(questionTitle) AGAINST(?)";
db.query(sqlSelect, searchTerm, (err, result) => {
res.send(result);
});
});
问题不在于查询,因为它在工作台中得到了肯定的结果,并且当我对用户输入的值进行硬编码时也可以正常工作。我收到一个错误:ER_PARSE_ERROR:您的 SQL 语法有错误;检查与您的 MySQL 服务器版本相对应的手册,以了解在 '?)' 附近使用的正确语法
我很难过,因为这是我的帖子,它按预期工作:
app.post('/answer/insert', (req, res, next)=> {
const question = req.body.question;
const answer = req.body.answer;
const category = req.body.category;
const today = req.body.today;
const sqlInsert = "INSERT INTO questions (questionTitle, questionBody, category, questionDate) VALUES (?,?,?,?)";
db.query(sqlInsert, [question, answer, category, today], (err, result) => {
console.log(err);
});
});
更新:前端看起来像这样
function startSearch(e) {
e.preventDefault();
console.log(searchTerm);
Axios.get('http://localhost:3001/api/get', {
searchTerm: searchTerm,
})
.then(function(response) {
console.log("It worked, response is: ", response)
}).catch(function() {
console.log("error");
});
};
我的帖子请求有效,它看起来像这样:
const submitReview = () => {
Axios.post('http://localhost:3001/answer/insert', {
question: question, answer: answer, category: category, today: today,
}).then(()=> {
console.log(category + question + answer + today);
alert('successful insert');
})
.catch(()=> {
console.log(category + question + answer + today);
alert('it didnt work');
})
}
【问题讨论】:
标签: mysql sql node.js reactjs express