What I'm trying to do is get json data from "/get" to "/", but I'm not sure why axios keeps giving my a 403 error. From what I read, axios isn't the issue, but cors is. I tried all the ways that people are recommending, but nothing is working. What I'm I doing wrong within my code? I'm also seeing "Referrer Policy: strict-origin-when-cross-origin" in the Header, but I'm not sure if that's what's causing this issue.
const express = require("express");
const mysql = require("mysql2");
var app = express();
const bodyparser = require("body-parser");
const cors = require("cors");
const cookieParser = require("cookie-parser");
const expressSession = require("express-session")({
secret: "secret",
resave: false,
saveUninitialized: false,
});
const passport = require("passport");
const jwt = require('jsonwebtoken');
app.use(passport.initialize());
app.use(passport.session());
app.use(bodyparser.json());
app.use(cors());
app.use(bodyparser.urlencoded({ extended: false }));
app.use(express.json());
app.use(cookieParser());
app.use(expressSession);
const axios = require('axios');
var mysqlConnection = mysql.createConnection({
host: "localhost",
user: "root",
password: "",
database: "sys",
multipleStatements: true,
});
mysqlConnection.connect((err) => {
if (!err) console.log("DB connection succeded.");
else
console.log(
"DB connection failed \n Error : " + JSON.stringify(err, undefined, 2)
);
});
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header('Access-Control-Allow-Methods', 'DELETE, PUT, GET, POST');
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
app.listen(5000, () =>
console.log("Express server is runnig at port no : 5000")
);
app.get("/get", authenticateToken, (req, res) => {
jwt.verify(req.token, 'secretpassword', (err) => {
if (err) {
res.sendStatus(403);
} else {
mysqlConnection.query("SELECT * FROM sys.jobs", (err, rows) => {
if (rows === undefined) {
res.send("Hello World!");
} else {
res.send(rows);
}
});
}
});
});
app.get("/", authenticateToken, (req, res) => {
jwt.verify(req.token, 'secretpassword', async (err) => {
if (err) {
res.sendStatus(403);
} else {
let response = await axios.get('http://localhost:5000/' +'get', {
withCredentials: true,
headers: {
'Access-Control-Allow-Origin': '*',
'Authorization': `Bearer
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6MSwiaWF0IjoxNjAwOTIyMTQ0LCJleHAiOjE2MDg2OTgxNDR9.aRsw-
jEQJ-7mlO10nBKA5VT3IL7P0b9T9K0C8aT8sUs`
}
});
res.send(response.data);
}
});
});
app.post("/login", async (req, res) => {
try {
const { email } = req.body;
mysqlConnection.query("SELECT * FROM sys.users WHERE email = ?", [email], async (error, results) => {
const id = results[0].id;
const token = jwt.sign({ id }, "secretpassword", {
expiresIn: '90d'
});
const cookieOptions = {
expires: new Date(
Date.now() + 90 * 24 * 60 * 60 * 1000
),
secure: false,
httpOnly: true
}
res.cookie('jwt', token, cookieOptions);
res.status(200).redirect("/get");
});
}
catch (error) {
console.log(error);
}
}
);
function authenticateToken(req, res, next) {
const bearerHeader = req.cookies.jwt;
if (typeof bearerHeader !== 'undefined') {
req.token = bearerHeader;
next();
} else {
res.sendStatus(403);
}
}
Hi,
I see multiple places where you're returning 403 status so I assume your request is not signed with token or its validation failed in some way.
Have you tried to run your code with ---inspect flag or set some logs in order to debug it?
Thank you for replying. I really appreciate your time.
Have you tried to run your code with
---inspectflag or set some logs in order to debug it?
Yes, but I'm still not seeing the issue. From what I read, it looks like I'm doing it correctly, but I believe there is a mirror mistake that I'm doing wrong.
I believe it's in the cors, but I tried multiple different ways to do it, but everything throws a 403 error in my axios saying "Request failed with status code 403"
I consoled logged my axios error below.
config: {
url: 'http://localhost:5000/get',
method: 'get',
headers: {
Accept: 'application/json, text/plain, /',
authorization: 'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6MSwiaWF0IjoxNjAxMDI5MTQ4LCJleHAiOjE2MDg4MDUxNDh9.ONWSevGx19eVrm9NEmkKvWcGbHTS-tbUmz5ZKRm2dsg',
'User-Agent': 'axios/0.20.0'
},
transformRequest: [ [Function: transformRequest] ],
transformResponse: [ [Function: transformResponse] ],
timeout: 0,
adapter: [Function: httpAdapter],
xsrfCookieName: 'XSRF-TOKEN',
xsrfHeaderName: 'X-XSRF-TOKEN',
maxContentLength: -1,
maxBodyLength: -1,
validateStatus: [Function: validateStatus],
data: undefined
},
request: ClientRequest {
_events: [Object: null prototype] {
socket: [Function],
abort: [Function],
aborted: [Function],
connect: [Function],
error: [Function],
timeout: [Function],
prefinish: [Function: requestOnPrefinish]
},
_eventsCount: 7,
_maxListeners: undefined,
outputData: [],
outputSize: 0,
writable: true,
_last: true,
chunkedEncoding: false,
shouldKeepAlive: false,
useChunkedEncodingByDefault: false,
sendDate: false,
_removedConnection: false,
_removedContLen: false,
_removedTE: false,
_contentLength: 0,
_hasBody: true,
_trailer: '',
finished: true,
_headerSent: true,
socket: Socket {
connecting: false,
_hadError: false,
_parent: null,
_host: 'localhost',
_readableState: [ReadableState],
readable: true,
_events: [Object: null prototype],
_eventsCount: 6,
_maxListeners: undefined,
_writableState: [WritableState],
writable: false,
allowHalfOpen: false,
_sockname: null,
_pendingData: null,
_pendingEncoding: '',
server: null,
_server: null,
parser: null,
_httpMessage: [Circular],
[Symbol(asyncId)]: 68,
[Symbol(kHandle)]: [TCP],
[Symbol(lastWriteQueueSize)]: 0,
[Symbol(timeout)]: null,
[Symbol(kBuffer)]: null,
[Symbol(kBufferCb)]: null,
[Symbol(kBufferGen)]: null,
[Symbol(kCapture)]: false,
[Symbol(kBytesRead)]: 0,
[Symbol(kBytesWritten)]: 0
},
connection: Socket {
connecting: false,
_hadError: false,
_parent: null,
_host: 'localhost',
_readableState: [ReadableState],
readable: true,
_events: [Object: null prototype],
_eventsCount: 6,
_maxListeners: undefined,
_writableState: [WritableState],
writable: false,
allowHalfOpen: false,
_sockname: null,
_pendingData: null,
_pendingEncoding: '',
server: null,
_server: null,
parser: null,
_httpMessage: [Circular],
[Symbol(asyncId)]: 68,
[Symbol(kHandle)]: [TCP],
[Symbol(lastWriteQueueSize)]: 0,
[Symbol(timeout)]: null,
[Symbol(kBuffer)]: null,
[Symbol(kBufferCb)]: null,
[Symbol(kBufferGen)]: null,
[Symbol(kCapture)]: false,
[Symbol(kBytesRead)]: 0,
[Symbol(kBytesWritten)]: 0
},
_header: 'GET /get HTTP/1.1\r\n' +
'Accept: application/json, text/plain, /\r\n' +
'authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6MSwiaWF0IjoxNjAxMDI5MTQ4LCJleHAiOjE2MDg4MDUxNDh9.ONWSevGx19eVrm9NEmkKvWcGbHTS-tbUmz5ZKRm2dsg\r\n' +
'User-Agent: axios/0.20.0\r\n' +
'Host: localhost:5000\r\n' +
'Connection: close\r\n' +
'\r\n',
_onPendingData: [Function: noopPendingOutput],
agent: Agent {
_events: [Object: null prototype],
_eventsCount: 2,
_maxListeners: undefined,
defaultPort: 80,
protocol: 'http:',
options: [Object],
requests: {},
sockets: [Object],
freeSockets: {},
keepAliveMsecs: 1000,
keepAlive: false,
maxSockets: Infinity,
maxFreeSockets: 256,
[Symbol(kCapture)]: false
},
socketPath: undefined,
method: 'GET',
insecureHTTPParser: undefined,
path: '/get',
_ended: true,
res: IncomingMessage {
_readableState: [ReadableState],
readable: false,
_events: [Object: null prototype],
_eventsCount: 3,
_maxListeners: undefined,
socket: [Socket],
connection: [Socket],
httpVersionMajor: 1,
httpVersionMinor: 1,
httpVersion: '1.1',
complete: true,
headers: [Object],
rawHeaders: [Array],
trailers: {},
rawTrailers: [],
aborted: false,
upgrade: false,
url: '',
method: null,
statusCode: 403,
statusMessage: 'Forbidden',
client: [Socket],
_consuming: false,
_dumped: false,
req: [Circular],
responseUrl: 'http://localhost:5000/get',
redirects: [],
[Symbol(kCapture)]: false
},
aborted: false,
timeoutCb: null,
upgradeOrConnect: false,
parser: null,
maxHeadersCount: null,
reusedSocket: false,
_redirectable: Writable {
_writableState: [WritableState],
writable: true,
_events: [Object: null prototype],
_eventsCount: 2,
_maxListeners: undefined,
_options: [Object],
_ended: true,
_ending: true,
_redirectCount: 0,
_redirects: [],
_requestBodyLength: 0,
_requestBodyBuffers: [],
_onNativeResponse: [Function],
_currentRequest: [Circular],
_currentUrl: 'http://localhost:5000/get',
[Symbol(kCapture)]: false
},
[Symbol(kCapture)]: false,
[Symbol(kNeedDrain)]: false,
[Symbol(corked)]: 0,
[Symbol(kOutHeaders)]: [Object: null prototype] {
accept: [Array],
authorization: [Array],
'user-agent': [Array],
host: [Array]
}
},
response: {
status: 403,
statusText: 'Forbidden',
headers: {
'x-powered-by': 'Express',
'access-control-allow-origin': '',
'access-control-allow-methods': 'DELETE, PUT, GET, POST',
'access-control-allow-headers': 'Origin, X-Requested-With, Content-Type, Accept',
'content-type': 'text/plain; charset=utf-8',
'content-length': '9',
etag: 'W/"9-PatfYBLj4Um1qTm5zrukoLhNyPU"',
date: 'Fri, 25 Sep 2020 13:11:57 GMT',
connection: 'close'
},
config: {
url: 'http://localhost:5000/get',
method: 'get',
headers: [Object],
transformRequest: [Array],
transformResponse: [Array],
timeout: 0,
adapter: [Function: httpAdapter],
xsrfCookieName: 'XSRF-TOKEN',
xsrfHeaderName: 'X-XSRF-TOKEN',
maxContentLength: -1,
maxBodyLength: -1,
validateStatus: [Function: validateStatus],
data: undefined
},
request: ClientRequest {
_events: [Object: null prototype],
_eventsCount: 7,
_maxListeners: undefined,
outputData: [],
outputSize: 0,
writable: true,
_last: true,
chunkedEncoding: false,
shouldKeepAlive: false,
useChunkedEncodingByDefault: false,
sendDate: false,
_removedConnection: false,
_removedContLen: false,
_removedTE: false,
_contentLength: 0,
_hasBody: true,
_trailer: '',
finished: true,
_headerSent: true,
socket: [Socket],
connection: [Socket],
_header: 'GET /get HTTP/1.1\r\n' +
'Accept: application/json, text/plain, */\r\n' +
'authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6MSwiaWF0IjoxNjAxMDI5MTQ4LCJleHAiOjE2MDg4MDUxNDh9.ONWSevGx19eVrm9NEmkKvWcGbHTS-tbUmz5ZKRm2dsg\r\n' +
'User-Agent: axios/0.20.0\r\n' +
'Host: localhost:5000\r\n' +
'Connection: close\r\n' +
'\r\n',
_onPendingData: [Function: noopPendingOutput],
agent: [Agent],
socketPath: undefined,
method: 'GET',
insecureHTTPParser: undefined,
path: '/get',
_ended: true,
res: [IncomingMessage],
aborted: false,
timeoutCb: null,
upgradeOrConnect: false,
parser: null,
maxHeadersCount: null,
reusedSocket: false,
_redirectable: [Writable],
[Symbol(kCapture)]: false,
[Symbol(kNeedDrain)]: false,
[Symbol(corked)]: 0,
[Symbol(kOutHeaders)]: [Object: null prototype]
},
data: 'Forbidden'
},
isAxiosError: true,
toJSON: [Function: toJSON]
}
GET on /get calls function authenticateToken [1], which requires a jwt cookie to be set [2] and your axios request does not send any cookies [3]:
// ...
app.get("/get", authenticateToken, (req, res) => { // [1] - call to authenticateToken
// ...
});
app.get("/", authenticateToken, (req, res) => {
// ...
let response = await axios.get('http://localhost:5000/' + 'get', { // Request "/get"
withCredentials: true,
headers: {
'Access-Control-Allow-Origin': '*',
'Authorization': `Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6MSwiaWF0IjoxNjAwOTIyMTQ0LCJleHAiOjE2MDg2OTgxNDR9.aRsw-jEQJ-7mlO10nBKA5VT3IL7P0b9T9K0C8aT8sUs`
// [3] NO "Cookie" HEADER HERE!!!
}
});
// ...
});
// ...
function authenticateToken(req, res, next) {
const bearerHeader = req.cookies.jwt; // [2.1] - cookie with name "jwt"
if (typeof bearerHeader !== 'undefined') { // [2.2] - must not be undefined
req.token = bearerHeader;
next();
} else {
res.sendStatus(403);
}
}
Closing this as it looks like not an issue in Express
GET on
/getcalls functionauthenticateToken[1], which requires ajwtcookie to be set [2] and your axios request does not send any cookies [3]:
Thank you for this. It works now.
Most helpful comment
GET on
/getcalls functionauthenticateToken[1], which requires ajwtcookie to be set [2] and your axios request does not send any cookies [3]: