axios POST request is not sent - node.js

Faced such a problem and can no longer solve it 2 days, please help.
There is a server on the nodejs:
index.js
const mongoose = require("mongoose");
const keys = require("./config/keys");
const app = require("./app");
const port = process.env.PORT || 3001;
mongoose
.connect(keys.MONGO_URL, { useNewUrlParser: true })
.then(() => {
app.listen(port, () => console.log(`Server started on port ${port}`));
console.log("Connected to" + " MongoDB");
})
.catch((error) => console.log(error));
app.js
const express = require("express");
const bodyParser = require("body-parser");
const cors = require("cors");
const morgan = require("morgan");
const passport = require("passport");
const authRoutes = require("./routes/auth");
const restaurantRoutes = require("./routes/restaurant");
const app = express();
app.use(passport.initialize());
require("./middleware/passport")(passport);
app.use(morgan("dev"));
app.use("/uploads", express.static("uploads"));
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(cors());
app.use("/api/auth", authRoutes);
app.use("/api/restaurant", restaurantRoutes);
module.exports = app;
Nested Routes:
router.get(
"/",
passport.authenticate("jwt", { session: false }),
controller.getAll
);
router.get(
"/:id",
passport.authenticate("jwt", { session: false }),
controller.getById
);
router.post(
"/create",
passport.authenticate("jwt", { session: false }),
upload.single("image"),
controller.create
);
router.patch(
"/update",
passport.authenticate("jwt", { session: false }),
upload.single("image"),
controller.update
);
router.delete(
"/:id",
passport.authenticate("jwt", { session: false }),
controller.delete
);
There is a request from the front:
export function createNewRestaurant(restaurant, token) {
return {
type: CREATE_NEW_RESTAURANT,
payload: axios({
type: "POST",
url: "api/restaurant/create",
headers: {
Authorization: token,
},
data: JSON.stringify(restaurant),
})
.then((response) => {
console.log(response);
// return response.data;
})
.catch((error) => {
console.log({ error });
// return error.response.data;
}),
};
}
The problem is that POST doesn't even get from the server ...
There is no mention of it in the server console
If you remove the line from package.json client
"proxy": "http://localhost:3001/"
and write in the request
url: "http://localhost:3001/api/restaurant/create",
then in the server console we will see the OPTIONS request
OPTIONS /api/restaurant/create 204 0.135 ms - 0
I understand that the case is CORS, but I have it installed and in theory should work it all out, but how does this happen?
In postman, the request goes fine

Related

req.cookies and req.signedcookies are empty

I'm storing cookies on my server, but when I tried to access them. Object Returns Null.
code I'm using to store my cookies. This is done when I'm logging in!
res.cookie("accessToken", accessToken, {
httpOnly: true,
secure: true,
expires: new Date(Date.now() + oneDay),
});
res.cookie("refreshToken", refreshToken, {
httpOnly: true,
secure: true,
expires: new Date(Date.now() + oneDay),
});
index.ts
const dotenv = require("dotenv");
dotenv.config();
const PORT = process.env.PORT || 3001;
const cookies = require("cookie-parser");
const express = require("express");
const app = express();
const cors = require("cors");
app.use(cors());
app.use(express.json());
app.use(cookies());
import dbConnect from "./db/connect";
import adminAuthRoter from "./routes/admin/adminAuthRouter";
app.get("/", (req: any, res: any) => {
res.send("Hello World");
});
app.use("/api/v1/adminauth", adminAuthRoter);
const start = async () => {
try {
await dbConnect(process.env.MONGODB_URI);
app.listen(PORT, () =>
console.log(`Server is listening on port ${PORT}...`)
);
} catch (error) {
console.log(error);
}
};
start();
When I tried to console.log(req.cookies) or console.log(req.signedCookies) my response is empty. But when I see my Postmon cookies there are cookies stored
Postmon Cookie Reponse Image
What may be the issue here?

why my console.log(req.body) give: {} in nodejs

I want to update a post in my bdd with the new value. When i click for validate i have an empty req.body!
exports.updatePost = (req, res, next) => {
Post.update(
{
message: req.body.message,
},
{ where: { id: req.params.id } }
)
.then(() => res.status(200).json({ message: "post modifié" }))
.catch((error) => res.status(500).json({ error }));
console.log(req.body)
console.log(req.params.id)
};
As you can see i console log my req.body for check, my req.paramas.id give me the right thing. Since i have this problem i decided to check my post route and my app.js but i didn't see anything.
my route is like this:
const express = require("express");
const router = express.Router();
const postCtrl = require("../controllers/post");
const auth = require("../middleware/auth");
const multer = require("../middleware/multer-configs");
//DIFFERENTE ROUTES POUR LES POSTS, COMPRENNANTS LES DIFFERENTS MIDDLEWARE UTILES ET D'AUTHENTIFICATION
router.get("/", auth, postCtrl.getAllPost);
router.post("/", auth, multer, postCtrl.createPost);
router.delete("/:id", auth, postCtrl.deletePost);
router.put("/:id", auth, postCtrl.updatePost);
router.get("/:id", auth, postCtrl.getPostByUserId);
module.exports = router;
and my app.js is like this:
const express = require("express");
require("dotenv").config();
const helmet = require("helmet");
const cors = require("cors");
const db = require("./models");
const path = require("path");
const bodyParser = require("body-parser");
const userRoutes = require("./routes/user");
const postRoutes = require("./routes/post");
const likeRoutes = require("./routes/like");
const commentRoutes = require("./routes/comment");
const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
//MODULE C.O.R.S
app.use(cors());
app.use(express.urlencoded({ extended: true }));
// POST
app.use("/api/post", postRoutes);
I don't really understand why my backend can't see the back or don't give me the result of my body.
my client side is like this actually:
const updatePost = () => {
if (textEdit) {
const data = new FormData();
data.append("message", textEdit);
axios.put(`http://localhost:5000/api/post/${id}`, data, {
headers: {
Authorization: `Bearer ${sessionStorage.getItem("authToken")}`,
},
})
.then((res) => {
console.log(res);
console.log(id)
console.log(message)
console.log(textEdit)
})
}
}

Reciving empty file objects from frontend to backend React and NodeJS

Hi I'm trying to upload a file to a server send with axios. To send it I use react with Hooks and UseState, the thing is that when I do the console.log of the file in de frontend it shows all correctly but when I send it to backend I recive it empty.
Here is an example about what shows the frontend with console.log():
Here is the function I use to send the 3 files to backend and the differents things like react Hooks and that which I need:
const [weight, setWeight] = useState("");
const [frontPhoto, setFrontPhoto] = useState({});
const [sidePhoto, setSidePhoto] = useState({});
const [backPhoto, setBackPhoto] = useState({});
const JWT = new ClassJWT();
const axiosReq = axios.create();
const [uploadErrors, setUploadErrors] = useState([{}]);
const upload = async (e) => {
e.preventDefault();
await JWT.checkJWT();
console.log(frontPhoto);
axiosReq.post("http://localhost:3001/upload-progress", {
weight,
frontPhoto,
sidePhoto,
backPhoto,
token: JWT.getToken()
}).then((response) => {
console.log(response);
if (response.data.statusCode === '200') {
} else {
}
});
};
And then, in the backend de console.log() is like this:
{
weight: '70',
frontPhoto: {},
sidePhoto: {},
backPhoto: {},
token: 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6MSwiaWF0IjoxNjI2NTk3Mjg1LCJleHAiOjE2MjY1OTgxODV9.njDz7BZX57NvAK399abQLhoelpTS4kStj4LBzjw5gR8'
}
Here is the router code I use to this upload:
routerProgress.post("/upload-progress", verifyJWT, async (req, res) => {
console.log(req.body);
}
And here is all the server configuration:
import express from 'express';
import sequelize from './db/db.js';
import cors from 'cors';
import fileUpload from 'express-fileupload';
// SERVER CONFIGURATION
const app = express();
const PORT = process.env.PORT || 3001;
app.listen(PORT, () => {
console.log(`Listening at ${PORT}`);
sequelize.sync({ force: false })
.then(() => console.log('Database Connected!'))
.catch(err => console.log(err));
});
// BODYPARSER
app.use(express.json({limit: '50mb'}));
app.use(express.urlencoded({ limit: '50mb', extended: true, parameterLimit: 50000}));
app.use(cors({
origin: ["http://localhost:3000"],
methods: ["GET", "POST"],
credentials: true
}));
app.use(fileUpload({
createParentPath: true
}));
// ROUTES
import { routerAuthentication } from './routes/authentication.js';
import { routerProgress } from './routes/progress.js';
app.use(routerAuthentication);
app.use(routerProgress);
I don't know how to solve it, I tried many things but anything doesn't word. Please if anyone know what can I do to solve it, I'll be very grateful with him. Thanks!

I cant access the req.user from passport outside of my routes folder. MERN stack redux node.js

I am trying to access the req.user that passport creates when doing a google o auth strategy. I can access the req.user in the routes file below, but when I try to access it in my userController file it is showing up as undefined.
Why is user accessible in routes file but not userController?
googleAuthRoutes.js:
const passport = require('passport');
const requireLogin = require('../middlewares/requireLogin')
const cors = require('cors');
const axios = require('axios');
const Template = require('../models/Template');
const corsOptions ={
origin: true,
credentials:true, //access-control-allow-credentials:true
optionSuccessStatus:200
}
module.exports = app => {
app.get('/auth/google',
passport.authenticate('google', {
scope: ['profile', 'email']
}));
app.get(
'/auth/google/callback',
passport.authenticate('google'),
(req, res) => {
res.redirect('/dashboard');
}
);
app.post('/templates/create', async (req, res) => {
const { template, body } = req.body
console.log(req.user)
const newTemplate = new Template({
template: template,
body: body,
_user: req.user.id
})
try {
await newTemplate.save()
return res.status(200).json({
message: "Successfully saved template"
})
} catch (err) {
return console.log(err)
}
});
app.get('/api/logout', cors(), (req, res) => {
req.logout();
res.redirect('http://localhost:3000');
});
app.get('/api/current_user', (req, res) => {
res.send(req.user);
})
}
when I call the res.send(req.user) here above it sends the user no problem
But it is undefined with the /templates/create route middleware.
the console.log(req.user) is coming back as undefined??
index.js:
const express = require('express');
const cors = require('cors')
const mongoose = require('mongoose');
const cookieSession = require('cookie-session');
const passport = require('passport');
const keys = require('./config/keys');
const bodyParser = require('body-parser')
require("dotenv").config();
require('./models/GoogleUserModel'); // the user model must be placed before this services passport// this must be ran after requiring model bcuz this needs the model. ORDER
require('./models/UserModel');
require('./services/passport');
const corsOptions ={
origin:'http://localhost:3000',
credentials: true, //access-control-allow-credentials:true
optionSuccessStatus:200
}
const app = express();
app.use(cors(corsOptions))
mongoose.connect(keys.mongoURI, {
useNewUrlParser: true,
useCreateIndex: true,
useUnifiedTopology: true
})
mongoose.connection.on('error', () => {
throw new Error (`unable to connect to database: ${keys.mongoURI}`)
});
app.use(bodyParser.json())
app.use(express.urlencoded( { extended: true }))
app.use(
cookieSession({
maxAge: 30 * 24 * 60 * 60 * 1000,
keys: [keys.cookieKey]
})
)
app.use(passport.initialize());
app.use(passport.session());
require('./routes/userRoutes')(app);
require('./routes/googleAuthRoutes')(app);
require('./routes/messageRoutes')(app);
app.use((err, req, res, next) => {
if (err.name === 'UnauthorizedError') {
res.status(401).json({"error" : err.name + ": " + err.message})
} else if (err) {
res.status(400).json({"error" : err.name + ": " + err.message})
console.log(err)
}
})
const PORT = process.env.PORT || 5000;
app.listen(PORT);
Again, Why is the req.user available in the app.get to /api/current_user but available in a post request to /templates/create?
Im trying to add the user.id to the schema when it saves so i can retrieve each template by the user.id and not show everyone everybody elses templates lol

express server returns 405 on routes in production

Im building an express instance for the first time and ive run into an issue where everything works locally, but when deployed sending a post request to the route responds:
Failed to load resource: the server responded with a status of 405
(Not Allowed)
Ive included the relevant code below:
server/index.js
const express = require('express');
const bodyParser = require('body-parser')
const path = require('path');
const app = express();
app.use(express.static(path.join(__dirname, 'build')));
const routes = require('./routes')(express)
require('./db')
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))
// parse application/json
app.use(bodyParser.json())
app.get('/', function (req, res) {
res.sendFile(path.join(__dirname, 'build', 'index.html'));
});
app.listen(process.env.PORT || 8080);
app.use('/', routes);
routes/index.js
var mongoose = require("mongoose");
const randomId = require('random-id');
const Submissions = require('../api/Submissions')
// routes/index.js
module.exports = (express) => {
// Create express Router
var router = express.Router();
// add routes
router.route('/submission')
.post((req, res) => {
let newSubmission = new Submissions(req.body);
newSubmission._id = randomId(17, 'aA0');
// Save the new model instance, passing a callback
newSubmission.save(function(err,response) {
if (err) {
console.log(err)
} else {
res.setHeader('Content-Type', 'application/json');
res.json({'success':true})
}
// saved!
})
});
return router;
}
client.js
let submission = {
name: this.state.newSubmission.name.trim(),
body: this.state.newSubmission.body.trim(),
email: this.state.newSubmission.email.trim(),
};
const requestOptions = {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(submission),
};
fetch("/submission", requestOptions)
.then((response) =>
response.json().then((data) => ({
data: data,
status: response.status,
}))
)
.then((res) => {
if (!res.data.success) {
notifier.warning('Failed to submit');
} else {
notifier.success('Submission successful');
}
});

Resources