Knex.js Error message when trying to insert into postgreSQL
const express = require("express");
const app = express();
const cors = require("cors");
const knex = require("./db/db");
//middlewares
app.use(cors());
app.use(express.json());
//routes
//creating a task
app.post("/task", async (req, res) => {
const { name } = req.body;
const newtask = await knex
.raw("insert into todo (name) values ($1)", [name])
.then(() => {
knex
.select()
.from("todo")
.then(() => {
res.send(newtask.row);
});
});
});
throw new Error( Expected ${expectedBindings} bindings, saw ${index}
); ^
Error: Expected 1 bindings, saw 0
You almost got it right. Replace your $1
with just a question mark (?)
and knex will allow it.
Also - the way you are combining await and.then doesnt make sense to me. To clarify what I would do:
const newTask = await knex.raw(‘INSERT INTO todo (name) VALUES (?);’, [name]);
const allTasks = await knex.from(‘todo’).select();
res.send(allTasks);
Another simplified way to do this with nicer knex syntax:
const newTask = await knex(‘todo’).insert({ name });
const allTasks = await knex(‘todo’).select();
res.send(allTasks);
Note that the response object doesnt contain rows
unless it is a raw query. Lastly, maybe check that name
actually exists after trying to destructure it - people will try sending the weirdest things online:)
Good luck!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.