Sqlite3 error message is shown on Postgresql application - node.js

I am learning to build an app using node express and knexjs to connect to the Postgresql database. When I do a post request, this warning message shows up. The data that I try to post is not in the database. Maybe the app thought I am using sqlite3?
sqlite does not support inserting default values. Set the useNullAsDefault flag to hide this warning. (see docs http://knexjs.org/#Builder-insert).
This is my server.js.
const express = require('express');
const app = express();
const path = require('path');
const knex = require('knex');
const bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
const database = knex({
client: 'pg',
connection: {
host : '127.0.0.1',
user : 'xxxxxxx',
password : 'xxxxxxx',
database : 'xxxxxxxxdb'
}
});
app.use(express.static(__dirname + '/../public/'));
app.get('/add_athlete', function(req, res) {
res.sendFile('add_athlete.html', {root: path.resolve(__dirname + '/../public/templates')});
});
app.post('/add_athlete', function(req, res) {
knex('participants').insert({
participant_number: 1,
email: "test#gmail.com",
first_name: "test",
last_name: "again"
})
.then (function () {
res.json({success: true, message: "ok"})
})
});
app.listen(3000);
console.log('Running at port 3000');

Just to make sure, this question has an answer.
As mentioned in the comments, you probably want to use the created database instance.
So instead of knex('participants').insert... you probably want to use database('participants').insert...

Related

request body is not working - MYSQL and Node JS

I'm trying to create this API with NodeJS, Express and Mysql but when testing on Postman, while the code is working to update the values on the database, it doesn't read the info I insert in the body of the request. For example, I can access the params info (codAluno), but not the request body (Empresa_Atual).
I have two files for the API: routes.js and index.js
const express = require('express')
const bodyParser = require('body-parser')
const app = express()
const db = require('./routes')
const port = 3000
app.use(
bodyParser.urlencoded({
extended: true,
})
)
app.use(bodyParser.json())
app.get('/', (request, response) => {
response.json({ info: 'API' })
})
app.get('/alunos', db.getAlunos)
app.get('/alunos/:id', db.getAlunoByCod)
app.post('/alunos/:id',db.updateAluno)
app.listen(port, () => {
console.log(`App running on port ${port}.`)
})
and routes.js
const mysql = require('mysql');
// Set database connection credentials
const config = {
host: 'localhost',
user: 'user',
password: '',
database: 'student',
};
// Create a MySQL pool
const pool = mysql.createPool(config);
const updateAluno = (request, response) => {
const codAluno = parseInt(request.params.id)
var Empresa_Atual = request.body.Empresa_Atual
pool.query('UPDATE aluno SET `Empresa_Atual`= ? WHERE `codAluno` = ?', [Empresa_Atual, codAluno], (error, result) => {
if (error) throw error;
response.send('User updated successfully.');
});
}
This is the request I'm sending via postman
For example, the variable Empresa_Atual is always null even though I assigned it to the request body.
Can anyone help?
Thanks!
I had the same problem. I had the following: req.params.id. I then changed it to req.params['id'] and it started working. Apparently, the req.params was an object instead of a single value.

Cannot Post to route

I am implementing a simple signup / login functionality in node js
But when using postman to post the router to localhost:3000/api/chatapp/register i am gettig error message
Cannot POST /api/register
CODE:
server.js
const express=require('express');
const mongoose=require('mongoose');
const cookiePaser=require('cookie-parser');
// const logger=require('morgan');
const app=express();
const dbConfig= require('./config/secret');
//adding middleware
app.use(cookiePaser()); //save our token in the cookie
// app.use(logger('dev')); // to display the url and http status code in the console
mongoose.Promise = global.Promise;
mongoose.connect(
dbConfig.url,{useNewUrlParser: true, useUnifiedTopology: true}
);
const auth=require('./routes/authRoutes');
app.use(express.json({limit: '50mb'})); //data coming in from form is limited up to 50 mb size
app.use(express.urlencoded({ extended: true, limit:'50mb'}));
app.use('/api/chatapp',auth);
app.listen(3000, () => {
console.log('Running on port 3000');
})
authRoute.js
const express=require('express');
const router=express.Router();
const AuthCtrl=require('../controllers/auth');
router.post('/register',AuthCtrl.CreateUser);
module.exports=router;
auth.js
module.exports={
CreateUser(req,res){
console.log(req.body);
}
};
userSchema.js
const mongoose = require("mongoose");
const userSchema = mongoose.Schema({
username: { type: String },
email: { type: String },
password: { type: String },
});
module.exports=mongoose.model('User',userSchema);
nodemon server and mongod are running fine
Postman result
for further details kindly look into my github repo :
https://github.com/Umang01-hash/chatApp-backend
Are you sure if that's the correct endpoint? Check out the folder structure and see this image for your answer.

Cannot GET /api/signup - Using Postman and mongodb

I am very new to mongoose and I made one signup api and while testing it using POSTMAN I'm getting these weird error as well when I refresh my http://localhost:8000/api/signup I get a message saying "Cannot GET /api/signup" and in my postman post request I am seeing an error message that says "Cannot POST /api/signup".
How would I get rid of these messages that are being displayed?
I am following a tutorial so I tried copying and pasting the code from the GitHub to make sure everything was perfect but I was still seeing these error messages.
My app.js file is:
const express = require("express");
const mongoose = require("mongoose");
const morgan = require("morgan");
const bodyParser = require("body-parser");
const cookieParser = require("cookie-parser");
require("dotenv").config();
// import routes
const userRoutes = require("./routes/user");
// app
const app = express();
// db
mongoose
.connect(process.env.DATABASE, {
useNewUrlParser: true,
useCreateIndex: true
})
.then(() => console.log("DB Connected"));
// middlewares
app.use(morgan("dev"));
app.use(bodyParser.json());
app.use(cookieParser());
// routes middleware
app.use('api', userRoutes);
const port = process.env.PORT || 8000;
app.listen(port, () => {
console.log(`Server is running on port ${port}`);
});
my routes/users.js file is:
const express = require("express");
const router = express.Router();
const { signup } = require("../controllers/user");
router.post("/signup", signup);
module.exports = router;
my controllers/users.js is:
const User = require("../models/user");
exports.signup = (req, res) => {
console.log("req.body", req.body);
const user = new User(req.body);
user.save((err, user) => {
if (err) {
return res.status(400).json({
error
});
}
res.json({
user
});
});
};
I am hoping to see a response in my browser that does not display an image that image that says Cannot GET api/signup and I am hoping that Postman is able to return data from my api
It means there is no corresponding router setting to /api/signup
I think router.post("/signup", signup); should be router.post("/api/signup", signup);
This should work fine on PostMan.
But the browser url is a get request, so the request would still fail. You will need to send the post request by javascript then.
For example, something like :
fetch('/api/signup', {
method: 'POST',
body: 'signup data here'
})
.then(response => response.json());
Please let me know if the error still exist.
There is a minor bug
app.use('api', userRoutes);
change to
app.use('/api', userRoutes);
My issue was that when I installed mongoDB locally I had not properly installed it and was not using a /data/db folder. I was able to fully uninstall my older version of mongoDB and reinstall everything following this youtube tutorial: https://www.youtube.com/watch?v=MIByvzueqHQ

How to properly query Postgresql database using pg with Node.js?

I am attempting to query a Postgresql database using Node, Express, and the pg module. I am getting the error "TypeError: Cannot read property 'query' of undefined"
I have looked at the node-postgres module website for the correct syntax as well as various other websites. I know that the syntax used to enable pg changed after pg version 6.3.0.
const express = require("express");
const path = require("path");
const bodyparser = require("body-parser");
const consolidate = require("consolidate");
const dust = require("dustjs-helpers");
const pg = require("pg");
var pool = new pg.Pool();
let app = express();
let connect = "postgres://postgres:secret#localhost:5432/my_database";
app.engine("dust", consolidate.dust);
app.set("view engine", "dust");
app.set("views", __dirname + "/views");
app.use(express.static(path.join(__dirname, "public")));
app.use(bodyparser.json());
app.use(bodyparser.urlencoded({extended: false}));
app.get("/", function(request, response, next) {
pool.connect(function(err, client, done) {
if (err) {
console.log(`Not able to get a connection: ${err}.`);
response.status(400).send(err);
}
client.query("SELECT * FROM recipes", function(err, result) {
done();
});
pool.end();
});
});
app.listen(3000, () => {
console.log("Server running on port: 3000");
});
Going to http://server_ip:3000 should show a webpage instead node crashes with this error:
client.query("SELECT * FROM recipes", function(err, result) {
^
TypeError: Cannot read property 'query' of undefined
You need to pass your connection string to pool when you instantiate it.
var pool = new pg.Pool({
connectionString: 'postgres://postgres:secret#localhost:5432/my_database',
});

Axios post request.body is empty object

I am trying to post data from my react. Backend - express.
Here is backend code:
var express = require('express');
var app = express();
var bodyParser = require("body-parser");
var methodOverride = require("method-override");
var mongoose = require("mongoose");
var expressSanitizer = require("express-sanitizer");
mongoose.connect("mongodb://localhost/blog-react");
//app config
app.set("view engine", "ejs");
app.use(express.static("public"));
app.use(bodyParser.urlencoded({extended: true}));
//must be after parser
app.use(expressSanitizer());
app.use(methodOverride("_method"));
//schema config
var blogSchema = new mongoose.Schema({
title: String,
image: String,
body: String,
//it should be date. With default value now.
created: {
type: Date, default: Date.now
}
});
var Blog = mongoose.model("Blog", blogSchema);
function handle500(response, error){
console.log(error.stack);
response.status(500);
response.json({error: "error: internal server error"});
}
app.post("/api/blogs", function(request, response){
var blog = {
title: request.sanitize(request.body.title),
image: request.sanitize(request.body.image),
body: request.sanitize(request.body.body)
};
console.log(request.body);
Blog.create(blog, function(error, newBlog){
if(error){
console.log("inside post handler ERROR")
handle500(response, error);
}
else{
console.log("inside post handler OK")
response.json({status: "success"});
}
});
});
React code:
var requestUrl = "/api/blogs";
var blog = {
title: "a",
image: "b",
body: "c"
}
axios.post(requestUrl, blog)
.then(function(response){
console.log("success",response.data)
})
.catch(function(response){
console.log("error", response);
});
When I post data via axios - request.body is always {}
But if I post data via regular form - all is correct - request.body contains all expected data.
What am I doing wrong with axios?
You are missing one middleware, bodyParser.json(). Add it to your configuration.
mongoose.connect("mongodb://localhost/blog-react");
app.set("view engine", "ejs");
app.use(express.static("public"));
app.use(bodyParser.json()); // <--- Here
app.use(bodyParser.urlencoded({extended: true}));
For people using Express>=4.16, bodyParser has been changed to the following:
app.use(express.json());
For me the issue was valid JSON format including double quotes on the variables.
This did not work
const res = await axios.post(serverPath + "/user/login", {
email: email,
password: password,
});
This DID work (with double quotes around email and password)
const res = await axios.post(serverPath + "/user/login", {
"email": email,
"password": password,
});
It looks like you only have two points left to make it work :
one : the http method should be set to POST instead of GET since you want to send something.
two : you can then add the http header (like what you did with the authorization header) Content-Type: 'application/json`
On the back-end don't forget to use some kind of body parser utility package like this one : body-parser and set it up with your app.
I suppose your server is using express, here is how you will do it with express :
const express = require('express');
const app = express();
const bodyParser = require('body-parser')
const jsonParser = bodyParser.json();
app.use(jsonParser); // use it globally
app.get('your_route', jsonParser, otherMiddleware, (req, res) => ...); // use it for specific routes
/* ... rest of your code */

Resources