Reputation: 1674
I am creating APIs in Nodejs using express and body-parser. I am able to successfully make the GET requests using postman but when using POST request it always throws error 404 not found Cannot GET /
Please check the code below
server.js file
require('dotenv').config();
const express = require("express");
const http = require("http");
var addRequestId = require('express-request-id')();
const requestIp = require('request-ip');
const cron = require("node-cron");
const cluster = require('cluster');
const os = require('os');
const v1 = require('./routes/v1');
const jobs = require('./routes/jobs/sync_job');
const bodyParser = require("body-parser");
// Check if current process is master.
if (cluster.isMaster) {
// Get total CPU cores.
const cpuCount = os.cpus().length;
// Spawn a worker for every core.
for (let j = 0; j < cpuCount; j++) {
cluster.fork();
}
var port = parseInt(3000);
var app = express();
var server = http.createServer(app);
app.use(addRequestId);
app.use(requestIp.mw())
app.use(bodyParser.json({limit: '50mb'}));
app.use(bodyParser.urlencoded({limit: '50mb', extended: false}));
server.listen(port, () => { })
console.log("SERVER UP AND RUNNING");
app.use('/v1/jp', require('./routes/report_center'));
}
cluster.on('exit', function (worker) {
console.log(`Worker ${worker.id} died'`);
console.log(`Staring a new one...`);
cluster.fork();
});
report_center.js
const moment = require('moment');
const express = require('express');
const bodyParser = require("body-parser");
const reports = express.Router();
const mysql = require('mysql');
const async = require("async");
const constants = require('./v1/constant.js');
var _ = require('lodash');
var pool = mysql.createPool({
connectionLimit: 1000,
host: process.env.DB_HOST,
port: process.env.DB_PORT,
user: process.env.DB_USER,
password: process.env.DB_PASS,
database: process.env.DB_DBNAME,
charset: process.env.DB_CHARSET,
timezone: 'UTC' + '05:30'
});
/*########################
Middleware Starts
#########################*/
reports.use(bodyParser.json());
reports.use(bodyParser.urlencoded({
extended: true
}));
reports.use(function (req, res, next) {
console.log(req.url)
pool.getConnection(function (err, con) {
if (err) {
res.send(JSON.stringify({
"error_status": true,
"error": constants.err_desc.error_409,
"message": constants.customMessage.DB_CON_FAILED
}))
} else {
var queryTofindClient = mysql.format(`select * from client where api_key = ? LIMIT 1;`, [req.headers['api_key']]);
console.log(queryTofindClient)
con.query(queryTofindClient, (err, queryTofindClient_res) => {
if (err) {
res.send(JSON.stringify({
"error_status": true,
"error": constants.err_desc.error_500,
"message": constants.customMessage.QUERY_FAILED
}))
} else {
if (queryTofindClient_res.length == 0) {
res.send(JSON.stringify({
"error_status": true,
"error": constants.err_desc.error_401,
"message": constants.customMessage.UNAUTHORISED
}))
} else {
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS,');
res.setHeader('Access-Control-Allow-Headers', 'origin, content-type, accept,x-access-token');
res.setHeader('Access-Control-Allow-Credentials', true);
res.setHeader('Content-Type', 'application/json');
next();
}
}
})
}
con.release();
})
})
/*########################
Middleware ENDS
#########################*/
reports.get("/get_api", function (req, res) {
console.log(req.body);
res.send('Ok');
});
reports.post("/post_api", function (req, res) {
console.log(req.body);
res.send('Ok');
});
module.exports = reports;
Upvotes: 0
Views: 1291
Reputation: 1674
After struggling for two days found the culprit known as a postman which was delivering my letters with a different sender name by which I mean it was just routing all the methods to GET type.
The below setting in the screenshot was turned off by default.
I just hope it helps someone who does not deserve to get frustrated and do save his time instead unlike like me
Upvotes: 1