我正在尝试通过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>