I am currently working on a project and there was a problem entering the mongo db input data:
app.js
const path = require('path');
const express = require('express');
const app = express();
const getAdminPannel = require('./routes/pannelRoute');
const getView = require('./routes/viewRoutes');
app.set('view engine', 'pug');
app.set('views',path.join(__dirname,'views'));
app.use(express.static(path.join(__dirname,'public')));
app.use(express.json());
app.use(express.urlencoded({extended:true}));
app.use('/api/v1/services',getAdminPannel);
//Views routes
app.use('/',getView);
module.exports = app;
routes folder
pannelRoute.js
const express = require('express');
const pannelController = require('../controller/pannelController');
const router = express.Router();
router.route('/create-services')
.post(pannelController.createPannelServices);
module.exports = router;
controller folder
pannelController
exports.createPannelServices = async(req,res) =>{
try{
const createService = Service.create(req.body);
console.log(req.body)
res.status(201).json({
length:createService.lengnth,
status:"Success",
data:{
services:createService
}
});
}catch(err){
res.status(400).json({
status:'Fail',
message:'Invalid data request'
});
}
}
script.js file where I take data from input sublit action:
import {createService} from './createService';
const createServices = document.querySelector('.createServiceForm');
if(createServices){
createServices.addEventListener('submit',(el)=>{
el.preventDefault();
const form = new FormData();
form.append('serviceName',document.getElementById('servicename_create').value);
form.append('serviceDescription',document.getElementById('serviceDescription').value);
createService(form)
})
}
createService.js script file where I use axios to inser data using api link.
import "regenerator-runtime/runtime";
import axios from 'axios';
import { showAlert } from './alert';
export const createService = async(data)=>{
try{
const create = await axios({
method:'POST',
url:'http://127.0.0.1:5000/api/v1/services/create-services',
service:data
});
if(create.data.status === 'success'){
showAlert('success','Servicul a fost creeat!!!');
window.setTimeout(()=>{
location.assign('/');
}, 1500);
}
console.log(data);
}catch(err){
showAlert('error','A aparut o problema in procesul de creeare a servicului!!!');
}
}
the problem is that req.body does not return any value is empty and that error also appears
In createService.js you aren't passing the data correctly to axios.
You'll want to change it to this:
const create = await axios({
method:'POST',
url:'http://127.0.0.1:5000/api/v1/services/create-services',
data:data
});
req.body on the backend corresponds to the data field, which you weren't populating before.
Try axios.post in the createService.js
const create = await axios.post(
'http://127.0.0.1:5000/api/v1/services/create-services',
data,
{ headers: data.getHeaders() }
);
//print body response
console.log(create.data);
Related
my code was perfectly working a couple of days ago and it suddenly stopped working it's connected to the mongodb cluster but i fail to receive response from the database everytime i send a request it's i tried reinstalling node reinstalling mongoose updating all packages but nothing seemed to work
keeps loading forever
and no response when i cancel it
here's the server.js code :
const express = require('express');
const bodyParser = require('body-parser');
const morgan = require('morgan');
const mongoose = require('mongoose');
const cors = require('cors')
require('dotenv/config');
const authJwt = require('./helpers/jwt')
const errorHandler = require('./helpers/error-handler')
const api = process.env.URL;
mongoose.connect(process.env.DATABASE,
{
useNewUrlParser:true,
useUnifiedTopology:true
})
.then(()=>{
console.log('connected to database')
})
.catch((err)=>{
console.log(err)
})
//variables
const app = express();
const port = 9090
//middleware calls
app.use(bodyParser.json());
app.use(morgan('tiny'));
app.use(express.Router())
//app.use('')
app.use(cors());
app.options('*',cors())
app.use(errorHandler)
app.use(authJwt)
const categoriesRouter = require('./routers/categories')
const productsRouter = require('./routers/products')
const ordersRouter = require('./routers/orders')
const usersRouter = require('./routers/users')
//Routers
app.use(`${api}/categories`,categoriesRouter)
app.use(`${api}/products`,productsRouter)
app.use(`${api}/users`,usersRouter)
app.listen(port,(req,res)=>
{
console.log('server is running in port '+ port )
})
here's one of the routers code :
const {Category} = require('../models/category')
const express = require('express');
const router = express.Router();
router.get('/',async(req,res)=>{
const categoryList = await Category.find();
if(!categoryList)
{
res.status(500).json({success:false})
}
res.status(200).send(categoryList);
})
router.get('/:id',async(req,res)=>{
const category = await Category.findById(req.params.id)
if(!category)
{
res.status(500).json({message:'The category with the given ID'})
}
res.status(200).send(category)
})
router.post('/',async(req,res)=>{
let category = new Category({
name:req.body.name,
icon:req.body.icon,
color:req.body.color
})
category = await category.save();
if(!category)
return res.status(404).send('the fag category cannot be created')
res.send(category)
})
router.delete('/:id', (req,res)=>{
Category.findByIdAndRemove(req.params.id).then(category=>{
if(category)
{
return res.status(200).json({success:true,message:'the category is deleted'})
}
else
{
return res.status(404).json({success:false,message:'the category is not found'})
}
}).catch(err=>{
return res.status(400).json({success:false , error: err})
})
})
router.put('/:id',async (req,res)=>{
const category = await Category.findByIdAndUpdate(
req.params.id,
{
name:req.body.name,
icon:req.body.icon,
color:req.body.color
},
//i want to return the new updated data
{ new:true }
)
if(!category)
{
return res.status(400).send('The category cannot be created!');
}
res.send(category);
})
module.exports = router;
just to let you know it was working a couple of days ago and now it just suddenly stopped working if there's anything i can do or if you've faced the same problem before please reach out
Make sure to send a proper response on the api side of code.
In the case that u are using the express framework, it could look something like this:
router.get('/', (req, res) => {
res.status(200).json({
your: data
})
})
with the following code I bring a report that is hosted on JasperReports Server (This works), the problem is when passing values that have % since it returns %25 in the route and generates an error, any way to solve this problem?
const express = require('express');
const axios = require("axios");
const app = express();
var bodyParser = require("body-parser");
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended:true}))
app.get('/prueba', function(req,res){
res.sendFile(__dirname+"/prueba.html");
});
app.post('/form-submit', async function(req,res){
try {
const url = "http://localhost:8080/jasperserver/rest_v2/reports/reports/Re013.pdf"
const params = {
AMB_OCULTO: req.body.AMB_OCULTO,
AMB : req.body.AMB,
INS : '%',
ORD_INI: req.body.ORD_INI,
ORD_FIN: req.body.ORD_FIN
}
const file = await axios.get(url, {
params: params,
responseType: "stream",
auth:{
username: "jasperadmin",
password: "jasperadmin"
}
})
res.writeHead(200,{"Content-Type":"application/pdf"})
file.data.pipe(res)
} catch (error) {
res.sendFile(__dirname+"/prueba.html");
console.log(error)
}
});
I created an api with express js for a react application, it is already working, today I needed to implement a new route, very similar to another that already exists, but this new route that I created today has a problem when I go to production, locally it works normally , but when I put it on the server it doesn't work, but the other one that is almost equal to this new one works perfectly. The new route just returns 404 Not Found.
This is my routes.js(I deleted the other routes to make it easier to see):
const routes = require('express').Router();
const authMiddleware = require("./middleware/auth");
const ConcursoController = require('./controller/Concurso/ConcursoController');
const InscriptionController = require('./controller/Inscription/InscriptionController');
routes.use(authMiddleware);
// This route works perfectly
routes.get("/concurso/:id/:status/anexos", [
ConcursoController.getAnexos
]);
// This route does NOT work, it only returns 404
routes.get("/inscription/:inscriptionId/:codConcurso/anexos", [
InscriptionController.getAnexos
]);
module.exports = routes;
This is my app.js:
require("dotenv").config()
const express = require('express');
const cors = require('cors');
const routes = require('./routes');
const path = require("path");
require('./databese/connection');
const app = express();
app.use(cors());
app.use(express.urlencoded({ extended: true }));
app.use(express.json());
app.use('/uploads', express.static(path.resolve(__dirname, '..', 'upload')));
app.use(routes);
module.exports = app;
And this below is my frontend function that calls the route:
async function handleDownloadAnexosFromInscription() {
if (inscriptionSelected === "") return;
setDownloadByInscriptionAnexosLoading(true);
try {
const result = await api.get(`/inscription/${inscriptionSelected.id}/${inscriptionSelected.cod_concurso}/anexos`);
let tempLink = document.createElement('a');
tempLink.href = result.data.file;
tempLink.download = result.data.filename;
tempLink.target = "_blank";
tempLink.click();
toast.success("Download successful.");
} catch (err) {
toast.error("Failed to download attachments, please try again.");
}
setDownloadByInscriptionAnexosLoading(false);
}
Here how is the implementation of const api:
import axios from "axios";
import { getToken } from "../util/auth";
const api = axios.create({
baseURL: "https://exemple.com",
});
api.interceptors.request.use(async config => {
const token = getToken();
if (token) {
config.headers.Authorization = `Bearer ${token}`;
}
return config;
});
export default api;
I've tried to use POST as the request method, I tried to change the request body type and nothing worked.
I am trying to build a web application using MVC pattern, but I have a problem with POST-request to "http://localhost:5000/api/device": postman POST request attempt
The problem only occurs on POST request, GET request is OK: get request
Code:
index.js
const express = require('express')
const sequelize = require('./db')
require('dotenv').config();
const path = require('path')
const models = require('./models/models')
const cors = require("cors")
const app = express();
const router = require('./routes/index')
const fileUpload = require('express-fileupload')
const errorHandler = require('./milddleware/ErrorHandlingMiddleware')
app.use(cors())
app.use(express.json())
app.use(express.static(path.resolve(__dirname, 'static')))
app.use(fileUpload({}))
app.use('/api', router)
app.use(errorHandler)
const PORT = process.env.PORT || 5000;
const db_start = async ()=>
{
try
{
await sequelize.authenticate();
await sequelize.sync();
app.listen(PORT, ()=>{console.log(`Server started on port ${PORT}`)})
}
catch (e)
{
console.log(e);
}
}
db_start()
routes/index.js
const Router = require('express')
const router = new Router();
const deviceRouter = require('./deviceRouter')
const typeRouter = require('./typeRouter')
const brandRouter = require('./brandRouter')
const userRouter = require('./userRouter')
router.use('/user', userRouter)
router.use('/device', deviceRouter)
router.use('/brand', brandRouter)
router.use('/type', typeRouter)
module.exports = router
routes/deviceRouter.js
const Router = require('express')
const DeviceController = require('../controllers/deviceController')
const router = new Router();
router.post('/', DeviceController.create)
router.get('/', DeviceController.getAll)
router.get('/:id', DeviceController.getOne)
module.exports = router
controllers\deviceController.js
const uuid = require('uuid')
const path = require('path')
const {Device} = require('../models/models')
const ApiError = require("../errors/ApiError")
class DeviceController
{
async create(req, res, next)
{
console.log(req);
try{
const {name, price, brandId, typeId, info} = req.body;
const {img} = req.files;
let fileName = uuid.v4() + ".jpg";
img.mv(path.resolve(__dirname, '..', 'static', fileName));
const device = await Device.create({name, price, brandId, typeId, img: fileName});
return res.json(device);
}
catch(e)
{
next(ApiError.badRequest(e.message));
}
}
async getAll(req, res)
{
const {brandId, typeId} = req.query
let devices;
if(!brandId && !typeId)
{
devices = await Device.findAll()
}
if(brandId && !typeId)
{
devices = await Device.findAll({where: {brandId}})
}
if(!brandId && typeId)
{
devices = await Device.findAll({where: {typeId}})
}
if(brandId && typeId)
{
devices = await Device.findAll({where: {brandId,typeId}})
}
return res.json(devices)
}
async getOne(req,res)
{
}
}
module.exports = new DeviceController()
I logged the request and saw that the request body came up empty and req.files is undefined.
I compared these router and controller with others and found no differences in structure.
What am I doing wrong?
You cannot retrieve files of form-data directly from req.files.
Use formidable (it's an npm package) to parse form-data and work with it easily. Here are the steps:
Run npm install formidable.
Import formidable and fs package in your controller script with:
const formidable = require('formidable')
const fs = require('fs');
Change your create function with this:
async create(req, res, next) {
let form = new formidable.IncomingForm()
form.keepExtensions = true
form.parse(req, async (err, fields, files) => {
// console.log('err', err)
// console.log('fields', fields)
if (err) {
next(ApiError.badRequest(err));
return;
}
const { name, price, brandId, typeId, info } = fields; // <-- fields contain all your text data. it's like req.body
const { img } = files; // <-- it should work now!
let fileName = uuid.v4() + ".jpg";
fs.writeFileSync(path.resolve(__dirname, '..', 'static', fileName), img);
const device = await Device.create({ name, price, brandId, typeId, img: fileName });
return res.json(device);
}
}
I have making an API using express and node.
Here is my app.js
const express = require('express');
const bodyParser = require('body-parser');
const dotenv = require('dotenv');
// setup dotenv to read environment variables
dotenv.config()
// Load Environment Varibles
const env = require('./utils/env');
// INIT MONGODB CONNECTION
require('./mongoose');
// create a new express application
const app = express();
// setup bodyparser middleware to read request body in requests
// we're only reading JSON inputs
app.use(bodyParser.json());
// Listen to API routes
const apiRoutes = require('./routes')
app.use('/api', apiRoutes);
// Start listening to requests
app.listen(env.PORT, () => {
console.log(`Server started on PORT ${env.PORT}`);
});
And here is the API routes that are being imported
const express = require('express');
const apiController = require('./apiController');
const apiValidator = require('./apiValidator');
const router = express.Router();
router.post('/login', apiValidator.loginUserValidator, apiController.loginUserController);
router.get('/rand', (req, res) => {
res.send('Some randon text');
});
module.exports = router;
Here is the middleware
const {
failureResponse
} = require('./../utils/response');
const errorcodes = require('./../utils/errorcodes');
const loginUserValidator = (req, res, next) => {
const user = req.body;
if (!user.username) {
return res.status(400).json(failureResponse(errorcodes.ERROR_INVALID_BODY_PARAMETER, "Invalid username"));
}
if (!user.password) {
return res.status(400).json(failureResponse(errorcodes.ERROR_INVALID_BODY_PARAMETER, "Invalid password"));
}
if (user.authTokens) {
delete user.authTokens;
}
next();
};
module.exports = {
loginUserValidator
};
Here is the controller
const User = require('./../models/user');
const {
successResponse,
failureResponse
} = require('./../utils/response');
const errorcodes = require('./../utils/errorcodes');
const loginUserController = async (req, res) => {
try {
const user = req.body;
// find if the user already exists
const existingUser = await User.findOne({
username: user.username
});
if (existingUser) {
// user exists. generate token and login user
console.log('Existing user login');
const token = existingUser.generateAuthToken();
return res.status(200).json(successResponse(token));
} else {
console.log('New user login');
const savedUser = await new User(user).save();
const token = savedUser.generateAuthToken();
return res.status(200).json(successResponse(token));
}
} catch (e) {
console.log(e);
return res.status(400).json(failureResponse(errorcodes.ERROR_SERVER_ERROR, "Unable to login user"));
}
};
module.exports = {
loginUserController
};
Here the issue is when I try to hit the login route from Postman, I am getting an error which says Could not get any response.
But when I hit the rand route, the output is correct.
So the issue isn't the arrangement of the code.
Why am I not able to use the login route here?