request body is not working - MYSQL and Node JS - 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.

Related

how to use make express endpoints listen to same server as mongoose (apollo server)

i currently have an apollo server interacting with my mongodb database running on a port (localhost or the port given from the host when deployed). i also have another file (app.js) for web scraping that has routes and uses express, running on a different port.
i want the app.js express logic to run on the same port as the call
server.listen({ port: port}) in index.js. how do i do this, please? essentially something like putting the app.get calls in the mongoose.connect which does not seem possible, but so you can get the idea.
moving all the logic in app.js to index.js so the server listens to mongoose, apollo, and all the express endpoints i have in one place on the same, single port.
//index.js
const { ApolloServer } = require('apollo-server');
const mongoose = require('mongoose');
const express = require("express");
const bodyParser = require('body-parser');
const nodemailer = require('nodemailer');
let port = process.env.port || 5000;
const typeDefs = require('./graphql/typeDefs');
const resolvers = require('./graphql/resolvers');
const { MONGODB } = require('./config.js');
const server = new ApolloServer({
typeDefs,
resolvers,
context: ({ req }) => ({ req })
});
mongoose.connect(MONGODB, { useNewUrlParser: true })
.then(() => {
console.log("MongoDB connected");
return server.listen({ port: port})
})
.then((res) => {
console.log(`Server running at ${res.url}`);
})
app.js (snippet) used for endpoints that return web scraping data
const express = require("express");
const cors = require('cors')
const cheerio = require('cheerio');
const axios = require('axios');
const app = express();
const port = 5001;
app.get("/events/", function(req, res) {
// redacted logic
let { zipCode } = req.query;
// Create a new yelpAPI object with your API key
let apiKey =[redacted];
let yelp = new yelpAPI(apiKey);
// Set any parameters, if applicable (see API documentation for allowed params)
let params = [{ location: zipCode }];
// Call the endpoint
yelp.query('events', params)
.then(data => {
// Success
res.send(data);
})
.catch(err => {
// Failure
console.log(err);
});
});
app.listen(port, () => console.log(`CORS-enabled web server listening on port ${port}!`));

Returning data to a user from an external API

i am trying to return the value of my search after using the node-spotify-api package to search for an artist.when i console.log the spotify.search ..... without the function search function wrapped around it i get the values on my terminal..what i want is when a user sends a request to the userrouter routes i want is to display the result to the user..i using postman for testing ..
This is the controller
const Spotify = require('node-spotify-api');
const spotify = new Spotify({
id: process.env.ID,
secret: process.env.SECRET,
});
const search = async (req, res) => {
const { name } = req.body;
spotify.search({ type: 'artist', query: name }).then((response) => {
res.status(200).send(response.artists);
}).catch((err) => {
res.status(400).send(err);
});
};
module.exports = {
search,
};
**This is the route**
const express = require('express');
const searchrouter = express.Router();
const { search } = require('./spotify');
searchrouter.route('/').get(search);
module.exports = searchrouter;
**This is my server.js file**
const express = require('express');
require('express-async-errors');
const app = express();
require('dotenv').config();
// built-in path module
const path = require('path');
// port to be used
const PORT = process.env.PORT || 5000;
// setup public to serve staticfiles
app.use(express.static('public'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.set('port', PORT);
const searchrouter = require('./route');
app.use('/search', searchrouter);
app.get('/', (req, res) => {
res.sendFile(path.resolve(__dirname, 'index.html'));
});
app.listen(PORT, (req, res) => {
console.log(`Server is listening on port ${PORT}`);
});
[that is my project structure][1]
Well Your Code has a bug
Which is
searchrouter.route('/').get(search);
You are using a get request and still looking for a req.body
const { name } = req.body;
name is going to equal to = undefined
and when this runs
spotify.search({ type: 'artist', query: name })
it's going to return an empty object or an error
req.body is empty for a form GET request
So Your fix is
change your get request to a post
searchrouter.route('/').post(search);

Auth. error when trying to query to my PostgreSQL on Azure

Im making an API to insert data into my PostgreSQL database hosted at Azure, I have disable SSL and added firewall exceptions in order to secure the conexion, but Im still having an Authentication error when trying to make a POST request, this is the error log:
I think all the credentials I have to provide are in correct:
This is the code of the API:
Am I missing something? Some light would be apreciate.
const express = require("express");
const bodyParser = require("body-parser");
const cors = require("cors");
const Pool = require("pg").Pool;
const pool = new Pool({
user: "LuisFulcrum#sensors",
host: "sensors.postgres.database.azure.com",
database: "postgres",
password: "notTheRealPassword",
port: 5432
});
const app = express();
app.use(cors());
app.use(bodyParser.json());
app.listen(8000, () => {
console.log(`Server is running, listening to port 8000`);
});
app.post("/api/v1/nodo2059e7", (req, res) => {
const { label, status, priority } = req.body;
pool.query(
"INSERT INTO nodo2059e7(fecha, temperatura, humedad, presionatmosferica, pm1, pm2, pm10) VALUES (NOW(),1 ,1 ,1 ,1 ,1, 1);",
[label, status, priority],
(error, results) => {
if (error) {
throw error;
}
res.sendStatus(201);
}
);
});
Seems the error is obvious that you provided the wrong password. I also tested your code on my side using my on Azure Postgres SQL:
const express = require("express");
const bodyParser = require("body-parser");
const cors = require("cors");
const Pool = require("pg").Pool;
const pool = new Pool({
user: "mgr#stanpgtest",
host: "stanpgtest.postgres.database.azure.com",
database: "my db name",
password: "my pass",
port: 5432
});
const app = express();
app.use(cors());
app.use(bodyParser.json());
app.listen(8000, () => {
console.log(`Server is running, listening to port 8000`);
});
app.post("/api/v1/nodo2059e7", (req, res) => {
const { label, status, priority } = req.body;
pool.query(
"select now()",
(error, results) => {
if (error) {
throw error;
}
res.send(results);
}
);
});
everything works as excepted :
Just try to reset your password on Azure portal and try again:

username is undefined using express js

i'm building an auth app using expressjs however i got this error cannot read property username is undefined , i tested it using postman
here is the code
i always have this error
app.js
const express = require('express')
const app = express()
const port = 3000
const client = require('./config/database')
const routes = require('./urls/routes')
const bodyParser = require('body-parser')
//database connection
client.connect(err => {
if (err) {
console.error('connection error', err.stack)
} else {
console.log('connected')
}
})
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))
// routes
app.use('',routes)
app.listen(port, () => {
console.log(`Example app listening at http://localhost:${port}`)
})
auth.js
const db = require('../../config/database')
//register
module.exports = (res, req) => {
const username = req.body.username
const email = req.body.email
const password = req.body.password
values = [username, email, password]
const query = 'insert into users(username,email,password) values($1,$2,$3)'
db
.query(query, values)
.then(res => console.log(res.rows[0]))
.catch(e => console.error(e.stack))
}
//login
The parameters of a route should be REQUEST followed by RESPONSE. You are using the other way around. Must have been an oversight, nevertheless.

Why my POST request work only with debugger?

I try to write CRUD and checking it up with Postman.
When I use a debugger at the end of the post request it's working.
Problem: When I remove the debugger and try to run the code nothing happens - only error: "Could not get any response". How can I make my post to work well without debugger?
***For example, I send this as JSON through postman like this:
{
"id":3,
"name": "Ron",
"phone": "01323133333"
}
this is the relevant code:
index.js:
const express = require('express');
const app = express();
db = require('./db');
app.use(express.static('public'));
const bodyParser = require('body-parser');
app.use(bodyParser.json());
const port = 1400;
app.listen(port,()=>{
console.log(`Server is running on port ${port}`);
})
//post request:
app.post('/user' , (req,res)=> {
const {body} = req,
{id,name,phone} = body
db.query(`INSERT INTO public.users(
id, name, phone)
VALUES (${id}, '${name}', '${phone}');`,(err,dbRes)=>{
if(err)
res.status(400).send(err);
else
{
res.send(dbRes.rows);
}
})
})
db.js:
const {Client} = require ('pg');
const client = new Client ({
user:'postgres',
host:'localhost',
database:'nodeapp',
password:'123456',
port:5432
})
client.connect();
module.exports = client;
Thank you !

Resources