This is my index.js file.
import "babel-polyfill";
import http from "http";
import express from "express";
import cors from "cors";
import bodyParser from "body-parser";
import middleware from "./middleware";
import create from "./api/create";
import envVariables from "./envVariables";
import db from "./db";
let app = express();
app.server = http.createServer(app);
// 3rd party middleware
app.use(
cors({
exposedHeaders: envVariables.corsHeaders
})
);
app.use(
bodyParser.json({
limit: envVariables.bodyLimit
})
);
app.use(middleware({ envVariables, db }));
// api router
app.use("/api/create", create({ envVariables, db }));
//error handling
app.use((err, req, res, next) => {
res.status(400).json(err);
});
app.server.listen(process.env.PORT || envVariables.SERVER_PORT, () => {
console.log(`Started on port ${app.server.address().port}`);
});
export default app;
Before calling 'api/create' route, I want a middleware to be called in which I have to validate my key. Below is my middleware index.js
const axios = require('axios');
import { Router } from 'express';
const getData = async() => {
try {
return axios.post(`https://ilp-ulamp/api/fetchToken`).then(response => {
return response.data;
}).catch(error => {
console.log(error)
})
} catch (error) {
console.log(error);
}
}
export default ({ config, db }) => {
let routes = Router();
let validateKey = async function(req, res, next) {
if(!req.body.authToken)
return res.status(401).send("Access denied. No token provided.");
else {
const resp = await getData();
if(resp.length === 0){
return res.status(403).send("Access denied");
}
else {
next();
}
}
}
return validateKey;
}
Here, the problem is, I am not getting the proper response when calling https://ilp-ulamp/api/fetchToken
endpoint. I checked in Postman, this API is giving proper response but when calling this inside a middleware, it is giving response as empty.
I am not sure that I am doing it properly.
Kindly help me with this issue.
Thanks in Advance!!