我试图通过 EJS 文件中的表单发送 POST 请求。提交表单后,数据将发布到我的http://localhost:4000/getFormData(这是我的客户端),然后我尝试将该数据发布到我的http://localhost:3000/user_create这是我的 API。
我使用 axios 发送这样的 POST 请求:
app.post("/getFormData",function(req,res){
console.log("POST route of 4000 is hit");
var firstName=req.body.create_first_name;
var lastName=req.body.create_last_name;
console.log(typeof firstName);
console.log(typeof lastName);
axios.post('http://localhost:3000/user_create',
{create_first_name: req.body.create_last_name,lastName: req.body.create_last_name},
{headers: {'Content-Type': 'application/json'}})
.then(function (response) {
console.log(response.config);
res.redirect("/getUsers");
})
.catch(function (error) {
console.log(error);
});
});
我的 API (localhost:3000) 正在为这样的发布请求提供服务:
app.post("/user_create",function(req,res){
const firstName=req.body.create_first_name;
const lastName=req.body.create_last_name;
console.log("Type: "+typeof firstName + " Data :"+firstName);
console.log("Type: "+typeof lastName + " Data :"+lastName);
const query="INSERT INTO users (first_name,last_name) VALUES (?,?)"
mysqlConnection.query(query,[firstName,lastName],(err, results, fields) => {
if (err){
console.log("Failed to insert new user "+err);
res.sendStatus(500)
return
}
console.log("Inserted into"+results.insertId);
res.sendStatus(200)
}) });
我的表格如下所示:
<form action="/getFormData" method="POST">
<input type="text" name="create_first_name" id="" placeholder="First name">
<input type="text" name="create_last_name" id="" placeholder="Last name">
<button>Submit</button>
</form>
