Request failed with status code 400 with axios - node.js

I am trying to use the login API I made using node, however, whenever I call the API using Axios, it gives me a request failed in the console.
This is how I use axios to call my method:
axios
.post(
"http://localhost:8080/staffMember/login",
{
email: "Fred#gmail.com",
password: "Flintstone",
},
{
headers: {
"Content-Type": "application/json",
},
}
)
.then((response) => {
console.log(response);
})
.catch((error) => {
console.log(error.message);
});
};
And this is my login page and console :
This is my backend configuration:
require("dotenv").config();
const mongoose = require("mongoose");
const express = require("express");
const app = express();
const staffMember = require("./routers/staffMember.router.js");
const hrMember = require("./routers/hrMember.router.js");
const academicMember = require("./routers/academic members/academicMember.router");
const headOfDepartment = require("./routers/academic members/headOfDepartment.router");
const courseInstructor = require("./routers/academic members/courseInstructor.router");
const courseCoordinator = require("./routers/academic members/courseCoordinator.router");
var cors = require("cors");
app.use(cors());
mongoose
.connect(process.env.DATABASE_CONN_STRING, {
useNewUrlParser: true,
useUnifiedTopology: true,
useFindAndModify: false,
useCreateIndex: true,
})
.then(() => {
console.log("DB connected");
})
.catch(() => {
console.log("DB connection failed");
});
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use("/staffMember", staffMember);
app.use("/hrMember", hrMember);
app.use("/academicMember", academicMember);
app.use("/courseInstructor", courseInstructor);
app.use("/courseCoordinator", courseCoordinator);
app.use("/headOfDepartment", headOfDepartment);
module.exports = app;

please try this
axios.post('YOUR_FULL_URL', {
username: 'api',
password: 'MY_PASSWORD',
grant_type: 'MY_GRANT_TYPE'
}, {
headers: {
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
}}).then(response => {console.log(response)})
.catch(error => {
console.log(error.response)
});

well, I do not know how is the backend configured, but you could start by stringyfing yow body
axios
.post(
"http://localhost:8080/staffMember/login",
JSON.strinfify({
email: "Fred#gmail.com",
password: "Flintstone",
}),
{
headers: {
"Content-Type": "application/json",
},
}
)
.then((response) => {
console.log(response);
})
.catch((error) => {
console.log(error.message);
});
};
If that does not do any change, then change the header instead
axios
.post(
"http://localhost:8080/staffMember/login",
{
email: "Fred#gmail.com",
password: "Flintstone",
},
{
headers: {
"Content-Type": "application/x-www-form-urlencoded",
},
}
)
.then((response) => {
console.log(response);
})
.catch((error) => {
console.log(error.message);
});
};
lil commercial
If you want to b'cum a master with axios checkout https://medium.com/#enetoOlveda/how-to-use-axios-typescript-like-a-pro-7c882f71e34a
or npm i -S axios-es6-class

Related

CORS express js dont save a cookie

I read a lot of questions like this but no one is usefull for me.
I have a MERN app. I use Heroku to deploy. In my local environent everithing works but in heroku the login crash. I use Cookies. and try every posible configuration.
Please help.
This is my login server:
login: async (req, res) => {
try {
const { email, password } = req.body;
const user = await Users.findOne({ email })
//console.log(user)
if (!user) return res.status(400).json({ msg: "Usuario inexistente" })
const isMatch = await bcrypt.compare(password, user.password)
if (!isMatch) return res.status(400).json({ msg: "Clave erronea" })
//If login success, craete access Token and refresh
const accesstoken = createAccessToken({ id: user._id })
const refreshtoken = createRefreshToken({ id: user._id })
//console.log(refreshtoken)
res.cookie('refreshtoken', refreshtoken, {
sameSite: 'strict',
httpOnly: true,
path: '/user/refresh_token',
maxAge: 7 * 24 * 60 * 60 * 1000 //7days
})
res.json({ accesstoken })
} catch (err) {
return res.status(500).json({ msg: err.message })
}
},
Here server conf.
//MIDDELEWARES
app.use(express.json())
app.use(cookieParser())
//app.use(cors())
/*app.use(cors({
credentials: true,
origin: 'https://gabymanualidades.herokuapp.com/'
}))*/
app.use(cors({origin: 'https://*****.herokuapp.com', methods: ['POST', 'PUT', 'GET', 'OPTIONS', 'HEAD'], credentials: true, headers: 'Authorization, X-API-KEY, Origin, X-Requested-With, Content-Type, Accept, Access-Control-Allow-Request-Method' }))
app.use(fileUpload({
useTempFiles: true
}))
And client:
const loginSubmit = async e => {
e.preventDefault()
try {
//await axios.post('/user/login', { ...user })
const res=await axios.post('/user/login', { ...user }, {
headers: {
'Content-Type': 'application/json'
},
withCredentials: true,
baseURL: "*****.herokuapp.com"
})
console.log(res)
localStorage.setItem('firstLogin', true)
//window.location.href = "/products";
} catch (err) {
alert(err.response.data.msg)
}
}
Thak you very much!
Screenshot:
It is as if I logged in without saving the cookie since then I can't get it again here:
useEffect(() => {
const firstLogin = localStorage.getItem('firstLogin')
if (firstLogin) refreshToken()
}, [])
const refreshToken = async () => {
try {
console.log("aca problema")
const res = await axios.get('/user/refresh_token', {
headers: {
'Content-Type': 'application/json'
},
withCredentials: true,
baseURL: "https://young-wildwood-03509.herokuapp.com/"
})
setToken(res.data.accesstoken)
setTimeout(() => {
refreshToken()
}, 10 * 60 * 1000)
} catch (err) {
alert(err.response.data.msg)
}
}
Server:
refreshToken: (req, res) => {
try {
//console.log(req.cookies)
const rf_token = req.cookies.refreshtoken;
if (!rf_token) return res.status(401).json({ msg: "Plase Login or registeer" })
jwt.verify(rf_token, process.env.REFRESH_TOKEN_SECRET, (err, user) => {
if (err) return res.status(400).json({ msg: "Plase Login or registerr" })
const accesstoken = createAccessToken({ id: user.id })
//res.json({user, accesstoken})
console.log({ accesstoken })
res.json({ accesstoken })
})
//res.json({ rf_token })
} catch (err) {
return res.status(500).json({ msg: err.message })
}
},

I am getting 404 error and 204 error when consuming backend (node,vuejs)?

When signing in with postman everything works fine. But when i am doing an axios request i get 404 error and directly after 204 error. When i render my vue.js page i get "cannot get api/auth/signin. Also I get a message somewhere that says user not found.
What i have tried:
Frontend: I tried with adding headers to my axios request. I console logged the data and it seems perfectly fine.
Backend: Changed deprecated body parsers.
Frontend Code:
Auth store
import axios from "axios";
const state = {
token: "",
users: [],
};
const getters = {};
const actions = {
async signIn(_, payload) {
const response = await axios.post(
"http://localhost:3000/api/auth/signin",
{ payload },
{
headers: {
"Content-Type": "application/json",
},
}
);
console.log(response.data);
console.log(response.headers);
console.log(response.status);
},
};
const mutations = {};
export default {
state,
getters,
actions,
mutations,
};
This is my backend:
Controller
//signin
exports.signin = (req, res) => {
User.findOne({
username: req.body.username,
})
.populate("roles", "-__v")
.exec((err, user) => {
if (err) {
res.status(500).send({ message: err });
return;
}
if (!user) {
return res.status(404).send({ message: "User Not found." });
}
var passwordIsValid = bcrypt.compareSync(
req.body.password,
user.password
);
if (!passwordIsValid) {
return res.status(401).send({
accessToken: null,
message: "Invalid Password!",
});
}
var token = jwt.sign({ id: user.id }, config.secret, {
expiresIn: 86400, // 24 hours
});
var authorities = [];
for (let i = 0; i < user.roles.length; i++) {
authorities.push("ROLE_" + user.roles[i].name.toUpperCase());
}
res.status(200).send({
id: user._id,
username: user.username,
email: user.email,
roles: authorities,
accessToken: token,
});
});
};
Route
module.exports = function (app) {
app.use(function (req, res, next) {
res.header(
"Access-Control-Allow-Headers",
"x-access-token, Origin, Content-Type, Accept"
);
next();
});
app.post(
"/api/auth/signup",
[
verifySignUp.checkDuplicateUsernameOrEmail,
verifySignUp.checkRolesExisted,
],
controller.signup
);
app.post("/api/auth/signin", controller.signin);
And my server
const express = require("express");
const bodyParser = require("body-parser");
const cors = require("cors");
const jwt = require("jsonwebtoken");
const mongoose = require("mongoose");
const Quote = require("./models/Quote");
const quoteRoute = require("./routes/quoteRoute");
const quoteController = require("../Maxico/controllers/quoteController");
const config = require("./config/config");
const verifySignup = require("./middlewares/verifySignUp");
const Role = require("./models/Role");
const app = express();
//Import routes
//const authRoute = require("./routes/auth");
var corsOptions = {
origin: "http://localhost:8080/?#/",
};
app.use(cors(corsOptions));
app.use(express.urlencoded({ extended: true }));
app.use(express.json()); //
const db = require("./models/Quote");
mongoose
.connect(
"url",
{
useNewUrlParser: true,
useUnifiedTopology: true,
useFindAndModify: false,
}
)
.then(() => {
console.log("Connected to the database!");
})
.catch((err) => {
console.log("Cannot connect to the database!", err);
process.exit();
});
app.use(express.json());
app.get("/", (req, res) => {
res.send("Welcome to homepage");
});
app.use("/quote", quoteRoute);
require("./routes/authRoute")(app);
//require("./routes/userRoute")(app);
// initial roles
Role.estimatedDocumentCount((err, count) => {
if (!err && count === 0) {
new Role({
name: "user",
}).save((err) => {
if (err) {
console.log("error", err);
}
console.log("added 'user' to roles collection");
});
new Role({
name: "moderator",
}).save((err) => {
if (err) {
console.log("error", err);
}
console.log("added 'moderator' to roles collection");
});
new Role({
name: "admin",
}).save((err) => {
if (err) {
console.log("error", err);
}
console.log("added 'admin' to roles collection");
});
new Role({
name: "superadmin",
}).save((err) => {
if (err) {
console.log("error", err);
}
console.log("added 'superadmin' to roles collection");
});
}
});
// set port, listen for requests
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}.`);
});
In my network tab the request pay load got sent like this:
{payload: {username: "jon", password: "password"}}
payload: {username: "jon", password: "password"}
But my postman only accepts this:
{username: "jon", password: "password"}
So in my action i sent like this:
const actions = {
async signIn(_, payload) {
console.log(payload);
const response = await axios.post(
"http://localhost:3000/api/auth/signin",
payload,
{
headers: {
"Content-Type": "application/json",
},
}
);
console.log(payload);
console.log(response.data);
console.log(response.headers);
console.log(response.status);
},
};

My Access is blocked by cors policy but after a certain number of requests. It is working fine when I start the server. but after that it stops

So the problem is I am trying to access the backend of my application but it is getting blocked by the above message. It works for 4-5 requested once I restart my server. But after that, its requests are getting added to the pending list. I am using react for the frontend and node js with PostgreSQL for the backend. I am not sure why this problem is happening with the website.
error-msg :
Access to XMLHttpRequest at 'https://athrv-ed-demo.herokuapp.com/events' from origin 'https://arthv-ed-demo.netlify.app' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Backend server code:
require("dotenv").config();
const express = require("express");
const app = express();
const cors = require("cors");
const port = process.env.PORT || 5000;
const routes = require("./routes");
const bodyParser = require("body-parser");
//middlewares
app.use(cors());
app.use(express.json());
app.use(require("morgan")("dev"));
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(function (req, res, next) {
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader(
"Access-Control-Allow-Methods",
"GET, POST, OPTIONS, PUT, PATCH, DELETE"
);
res.setHeader("Access-Control-Allow-Credentials", true);
next();
});
//running the express app here
app.use("/", routes);
app.listen(port, () => {
console.log(`My app is running at ${port}`);
});
Here is the front-end code from where I am making the calls. The same thing is happening with both API.
const axios = require("axios");
const url = "http://localhost:5000";
// const url = "https://athrv-ed-demo.herokuapp.com";
export async function getevents() {
console.log("Preload triggered at index");
return await axios({
url: `${url}/events`,
method: "GET",
headers: {
mode: "no-cors",
Accept: "application/json",
},
})
.then((response) => {
// console.log("events recieved, From axios");
// console.logponse.data);
return response.data;
})
.catch((err) => {
// console.log("events not recieved, error in axios" + err);
return false;
});
}
export async function eventedit(event) {
// console.log("edit event is clicked");
return await axios({
url: `${url}/eventedit/${isAuthenticated().user.uid}/${event.eid}`,
method: "PUT",
headers: {
mode: "no-cors",
Accept: "application/json",
Authorization: `Bearer ${isAuthenticated().token}`,
},
})
.then((response) => {
// console.log("view toggled !, From axios");
// console.log(response.data);
return response.data;
})
.catch((err) => {
// console.log("view couldn't be toggled, error in axios" + err);
return false;
});
}
export async function getlist(event) {
return await axios({
url: `${url}/getlist/${isAuthenticated().user.uid}/${event.eventno}`,
method: "GET",
headers: {
mode: "no-cors",
Accept: "application/json",
Authorization: `Bearer ${isAuthenticated().token}`,
},
})
.then((response) => {
// console.log("got all peoples !, From axios");
// console.log(response.data);
return response.data;
})
.catch((err) => {
console.log("couldn't get all people, error in axios" + err);
return false;
});
}
export async function register(user) {
return await axios({
url: `${url}/registration`,
method: "POST",
data: {
name: user.name,
age: user.age,
phone: user.phone,
email: user.email,
college: user.college,
eventno: user.eventno,
},
headers: {
mode: "no-cors",
Accept: "application/json",
"Content-Type": "application/json",
},
})
.then((response) => {
// console.log("registration done!, From axios");
// console.log(response.data);
return response.data;
})
.catch((err) => {
// console.log("registration not done, error in axios" + err);
return false;
});
}
export async function signin(user) {
return await axios({
url: `${url}/signin`,
method: "POST",
data: {
email: user.email,
password: user.password,
},
headers: {
mode: "no-cors",
Accept: "application/json",
"Content-Type": "application/json",
},
})
.then((response) => {
// console.log("data from axios and signin successfull ");
// console.log(response.data);
return response.data;
})
.catch((err) => {
// console.log(user.password + " " + user.email);
// console.log("Error in axios {email and password doesn't match}");
return false;
});
}
export const signout = () => {
if (typeof window !== "undefined") {
localStorage.removeItem("jwt");
return axios({
url: `${url}/signout`,
method: "GET",
})
.then((response) => {
console.log("Signout Successfull from Axios");
})
.catch((err) => {
console.log(err);
});
}
};
export async function postevent(event) {
return await axios({
url: `${url}/postevent/${isAuthenticated().user.uid}`,
method: "POST",
data: {
name: event.name,
date: event.date,
},
headers: {
mode: "no-cors",
Accept: "application/json",
Authorization: `Bearer ${isAuthenticated().token}`,
},
})
.then((response) => {
// console.log("new event posted!, From axios");
// console.log(response.data);
return response.data;
})
.catch((err) => {
// console.log("Couldn't post, error in axios" + err);
return false;
});
}
export const authenticate = (data, next) => {
if (typeof window !== "undefined") {
localStorage.setItem("jwt", JSON.stringify(data));
next();
}
};
export const isAuthenticated = () => {
if (typeof window == "undefined") {
return false;
}
if (localStorage.getItem("jwt")) {
return JSON.parse(localStorage.getItem("jwt"));
} else {
return false;
}
};

Hapi unknown authentication strategy jwt

I'm getting the error Hapi unknown authentication strategy jwt but I'm not sure why. I'm certain I've probably set something up wrong but here's my server index.js:
Should i be using a different auth strategy? Also stackoverflow won't let me submit my question because it's mostly code but I'm not sure what else to submit. All of the details are here and I don't know what else to add to provide any more information that i can. I'm just using using auth with config.auth.strategy and jwt in an array.
const Hapi = require('#hapi/hapi');
const objection = require('objection');
const knex = require('./knex');
const authService = require('./auth/auth-service');
const JWTAuth = require('hapi-auth-jwt2');
const init = async () => {
const server = Hapi.server({
port: 9000,
host: 'localhost',
routes: { cors: {
origin: ['*'],
headers: ['Authorization'],
exposedHeaders: ['Accept'],
additionalExposedHeaders: ['Accept'],
maxAge: 60,
credentials: true
}}
});
objection.Model.knex(require('./knex'));
await server.register([
{plugin: JWTAuth},
{
plugin: require('./movies/movie-routes'),
routes: {prefix: '/movies'}
}, {
plugin: require('./user/user-routes'),
}
])
server.auth.strategy('jwt', 'jwt',{
key: authService.jwtKey,
validate: authService.validateJWT,
verifyOptions: {algorithms: ['HS256']},
errorFunc: (err)=> {return err},
cookieKey: 'id_token'
})
await server.start();
console.log('Server running on %s', server.info.uri);
};
process.on('unhandledRejection', (err) => {
console.log(err);
process.exit(1);
});
init();
Seems like there is a problem with authService.validateJWT I have added an example of HapiJs jwt authentication please it once for your reference
const Hapi = require('#hapi/hapi');
const JWTAuth = require('hapi-auth-jwt2');
const init = async () => {
const server = Hapi.server({
port: 9000,
host: 'localhost',
routes: {
cors: {
origin: ['*'],
headers: ['Authorization'],
exposedHeaders: ['Accept'],
additionalExposedHeaders: ['Accept'],
maxAge: 60,
credentials: true
}
}
});
await server.register([
{ plugin: JWTAuth }
])
server.auth.strategy('jwt', 'jwt', {
key: 'your-key',
validate: async function (decoded, request) {
if (!decoded) {
return { isValid: false };
} else {
request.auth.credentials = {
'user': decoded,
'token': request.headers['authorization']
};
return { isValid: true };
}
},
verifyOptions: { algorithms: ['HS256'] },
cookieKey: 'id_token'
});
server.auth.default('jwt');
server.route({
method: 'GET',
path: '/',
handler: (request, h) => {
return 'Hello World!';
}
});
await server.start();
console.log('Server running on %s', server.info.uri);
};
process.on('unhandledRejection', (err) => {
console.log(err);
process.exit(1);
});
init();

Axios request body are parsed strangely in the express server

I have nodejs express server and nodejs axios client, I tried send post data with x-www-form-urlencoded header.
app.post('/login', (req, res) => {
const { username, password } = req.body
console.log(req.body)
})
request body from nodejs axios client:
{ '{"username":"gefalko","password":"mypass"}': '' }
request body from postman client:
{"username":"gefalko","password":"mypass"}
I use 'body-parser' https://www.npmjs.com/package/body-parser middleware for request body parsing on the server.
app.use(bodyParser.urlencoded({ extended: true }))
app.use(bodyParser.json())
and my axios code looks like:
const axios = require('axios')
const prompt = require('prompt')
var prompt_attributes = [
{
name: 'username',
validator: /^[a-zA-Z\s\-]+$/,
warning: 'Username is not valid, it can only contains letters, spaces, or dashes'
},
{
name: 'password',
hidden: true
}
]
prompt.start();
prompt.get(prompt_attributes, function (err, result) {
if (err) {
console.log(err);
return 1;
}else {
console.log('Command-line received data:');
const username = result.username
const password = result.password
const config = {
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
}
const reqBody = {
username: username,
password: password
}
axios.post('http://localhost:3005/login', reqBody, config).then(response => {
console.log(response.data);
}).catch(error => {
console.log(error);
})
}
});

Resources