我使用Express制作api,并使用angular发送POST请求,但不知为何请求无法发送,我不知道原因。
服务器
app.post('/users/register', (req, res) => {
const { first_name, last_name, email, password, city, street } = req.body
pool.query('INSERT INTO users SET ? ', {first_name,last_name,email,password,city,street }, (err, data) => {
if(err) {
console.log(err);
} else {
console.log(data);
res.status(200).send(data)
}
})
})
服务
insertUsers(registerFrom) {
return this.http.post('http://localhost:3000/users/register', registerFrom)
}
组成部分TS
submitFrom(registerForm) {
console.log(registerForm);
this.appControl.insertUsers(registerForm)
.subscribe(data => {
console.log(data);
})
}
组件html
<form #registerFrom="ngForm" (ngSubmit)="submitFrom(registerFrom.value)" class="form-container sign-up-container">
<div class="thisForm">
<h1>Create Account</h1>
<div >
<input type="checkbox" id="admin" name="admin" value="Admin">
<label for="admin"> Admin?</label>
</div>
<div class="social-container">
<span>or use your account</span>
</div>
<input ngModel name="name" type="text" placeholder="First name" />
<input ngModel name="lastName" type="text" placeholder="Last name" />
<input ngModel name="email" type="email" placeholder="Email" />
<input ngModel name="password" type="password" placeholder="Password" />
<div class="adress">
<input name="city" ngModel type="text" placeholder="City">
<input name="street" ngModel type="text" placeholder="Street">
</div>
<button type="submit" value="Submit">Sign Up</button>
</div>
</form>
在服务器上用数组代替对象
pool.query('INSERT INTO users SET ? ', [first_name,last_name,email,password,city,street, (err, data) => {}
试试查询。
pool.query('INSERT INTO users ( first_name, last_name, email, password, city, street ) VALUES (?,?,?,?,?,?)', [first_name, last_name, email, password, city, street]), function (error, results) {
if (error) throw error;
// ...
});
并查看关于转义查询值的文档。https:/www.npmjs.compackagemysql#escaping-query-values
为了避免SQL注入攻击,在SQL查询中使用任何用户提供的数据之前,你应该总是转义。