I am making a notes api. When inserting from my endpoint, I get the error that the title cannot be null even though I pass it as a parameter. This is the code I have. It's the only thing that fails me, the rest works fine.
const insertNote = (req, res) => {
const { titulo, descripcion } = req.params
const sql = "INSERT INTO notas (id, titulo, descripcion, completado) VALUES('', ?, 0)"
connection.query(sql, {titulo, descripcion}, (err, result) => {
if(err) throw err
})
}
As you can see I have the sql query and the parameters that I assign to it. But when doing the post from my rest client I get the following error:
I have tried to change the structure of the query. But still it fails me.
edit
I have gone through the console log the vafriables and they come out as undefined. On request this is how I handle the route
router.put("/api/upload/", controller.insertNote)
I have also tried changing the method to post and nothing. This is how I send the requests from the client along with the error message it shows me
edit 2
I have tried to install bodyParser following a tutorial and now the variables do receive the data. But the client stays in a loop processing the request and never sends it.
This is the current status of the problematic feature
const insertNote = (req, res) => {
const titulo = req.body.titulo
const descripcion = req.body.descripcion
const sql = "INSERT INTO notas (id, titulo, descripcion, completado) VALUES('', ?, 0)"
console.log(titulo)
console.log(descripcion)
connection.query(sql, {titulo, descripcion}, (err, result) => {
if(err) throw err
})
}
edit 3
This is what appears in the MySQL table when I now send the request
The data I sent should appear in the last three registers. But it's not like that
edit 4
I have changed the object that received the parameters for an array and now the client is frozen in an infinite loop when sending the request. But the data is saved correctly
ISSUE
You want to get 2 values sent in a request
http
to an API developed with Express . The values will be used to update a MySQL table by inserting a new record.Among the problems that are observed in the code, I must highlight that you are trying to use
req.params
, but the route that you are trying to consume does not have any parameters configured:In your question you also say that you have tried to pass the values in the request body and have installed and configured a library called
body-parser
. However, if you use ExpressJS v.4.16 or higher, it is not necessary to install this library since it comes by default as part ofexpress
.SOLUTION
Assuming that you want to effectively use parameters in the URL you consume, then you must create the proper routing on it.
For example:
In this way I am telling Express to handle the route in such a way that the title and description values are part of the route, that is, they are parameters.
As you can imagine, this is not the most suitable for what you are trying to do, since by default the values passed by the URL will be encoded. For example, if a description is very long: "Hello, this is a test note", the result of the URL to consume will look like this:
Being the title: "Test" and the description: "Hello%2C%20this%20is%20a%20note%20from%20test"
As you can see, it may not be the best way to send this type of data to the server.
Using the
body
or request bodyThe best thing in these cases is to send the information in the body of the request. To do this you could send the serialized data in JSON format.
In order to read data from the request body, Express needs to parse the request body. This is where the body parser comes into play . Express has 2 methods to achieve the goal:
express.json()
: is a middleware that parses incoming requests for a JSON Payload.express.urlencoded()
: is a middleware function that parses incoming requests and looks for urlencoded Pyloads.Without going into too much detail about how both methods work, I'm simply suggesting that you use both as an essential part of your application, remembering to use them before the declaration of any routes where they are required. For example, to have it available on any route throughout your application, you can do it like this:
Once we have used the middleware to parse the request body correctly, we can then move on to the second part of the problem.
Update yes and only if we can do it
One of the problems with your code is that it takes things for granted. In other words, it fails simply because at no time do you take on the task of verifying whether or not you can insert a new record.
One of the golden rules in backend development is: "NEVER TRUST WHAT THE CLIENT SUBMITS".
Your method for updating the table might look something like this:
In the code above you can see that a response is sent to the client at all times with
return res.status()...
. In this way the client will know that the request has been processed by the server and it receives a response.The first thing to do is get the title and description values from the request body:
We then check that the title values are not empty strings,
null
nor areundefined
. If one or both of them is of this type, we return a message to the client to indicate that the request has not been processed because there is an error in it. That is why the response status is set to 400 (Bad Request).Finally, we create the prepared statement for inserting the data into the database.
I don't know how you have your table set up, but usually the value of
id
is auto numeric and auto generated by the database engine. Also the field valuecompletado
could be automatically inserted into an insert by a default value. But in general you only have to check that the values passed in the object that receives the methodquery
are the right ones and necessary to be able to carry out the operation on the database.As for the way to send the data from the client to the server, this will depend a lot on the type of client you are using. An image of what I assume POSTMAN is is shown in your question. So sending the data in the request body the way Postman does is more than enough.
I hope this helps you solve the problem.