Node.js POST method error 404 - node.js

I built an index.js file which sends SMS based on body input while posting with Postman. The code is working and looks like this (I have hidden my apiKey and apiSecret for this preview)
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
const Nexmo = require('nexmo');
const nexmo = new Nexmo({
apiKey: 'hidden.apiKey',
apiSecret: 'hidden.apiSecret'
});
app.post('/send', (req, res) => {
// Sending SMS via Nexmo
nexmo.message.sendSms(
'4542542445', req.body.toNumber, req.body.message, {type: 'unicode'},
(err, responseData) => {if (responseData) {console.log(responseData)}}
);
});
const server = app.listen(3000);
console.log("starting server")
It woks fine and I receive an SMS message when I run the file, and a post to the route using Postman.
I am trying to implement the same in my bigger project, where I have separate client and server folders representing my frontend and backend.
When I add the code to my app.js file, I run into Status code 404 not found error. Here is the code of my app.js:
const express = require('express')
const bodyParser = require('body-parser')
const cors = require('cors')
const morgan = require('morgan')
const {sequelize} = require('./models')
const config = require('./config/config')
const Nexmo = require('nexmo')
const app = express()
app.use(morgan('combined'))
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: false}))
app.use(cors())
require('./routes')(app)
sequelize.sync()
.then(() => {
app.listen(config.port)
console.log(`Server started on port ${config.port}`)
})
const nexmo = new Nexmo({
apiKey: 'hidden.apiKey',
apiSecret: 'hidden.apiSecret'
}, {debug: true})
app.post('/send', (req, res) => {
// Sending SMS via Nexmo
nexmo.message.sendSms(
'4542542445', req.body.toNumber, req.body.message, {type: 'unicode'},
(err, responseData) => {if (responseData) {console.log(responseData)}}
);
});
I am asking for help to try figure out what is wrong and why it does not hit the route, instead returning status code 404.
I can share my github or we can talk on discord: soko#8667
I appreciate your thoughts and help.

Routes in express should be written :
let route = require('routes');
app.use('/', route);

I managed to make it work.
I was adding new route while my server was running.
I restarted my PC and ran server and client again and it seems work.

Related

Route does not exist on the browser but it works fine on the postman

Okay so i just started building an api using Node. Normally, before i even start, i test it in the postman using dummy data to make sure all the routes are working fine but i never tested it on the browser until today. It brings out the dummy data all fine in the postman but when I put in the same route i used in the postman on the browser tab, it just brings out my custom error message "Route does not exist". Why is this happening?
This is my routes/auth.js
const express = require('express')
const router = express.Router()
const {upload} = require('../utils/multer')
const { register, login } = require('../controllers/auth')
router.post('/register', upload.single('picture'), register)
router.post('/login', login)
module.exports = router
This is my controllers/auth.js:
const register = async (req, res) => {
res.send('register')
}
const login = async (req, res) => {
res.send('login')
}
module.exports = {register, login}
This is my app.js:
require('dotenv').config()
require('express-async-errors');
const bodyParser = require('body-parser')
const cors = require('cors')
const multer = require('multer')
const helmet = require('helmet') //helps you secure your Express apps by setting various HTTP headers.
const morgan = require('morgan')
const path = require('path')
const express = require('express');
const app = express();
/* CONFIGURATIONS */
app.use(helmet());
app.use(helmet.crossOriginResourcePolicy({ policy: "cross-origin" }));
app.use(morgan("common"));
app.use(bodyParser.json({ limit: "30mb", extended: true }));
app.use(express.urlencoded({ limit: "30mb", extended: true }));
app.use("/assets", express.static(path.join(__dirname, "public/assets")));
//routers
const authRouter = require('./routes/auth')
// error handlers
const notFoundMiddleware = require('./middleware/not-found');
const errorHandlerMiddleware = require('./middleware/error-handler');
//middleware
app.use(express.json());
app.use(cors());
//routes
app.use('/api/v1/auth', authRouter)
//errors
app.use(notFoundMiddleware);
app.use(errorHandlerMiddleware);
//database
const connectDB = require('./db/connect');
const port = process.env.PORT || 5000;
const start = async () => {
try {
await connectDB(process.env.MONGO_URI);
app.listen(port, () =>
console.log(`Server is listening on port ${port}...`)
);
} catch (error) {
console.log(error);
}
};
start();
Please note that i do not understand what most of these configurations do, not very well anyways. i have tried to remove them though but the problem was still there.
I am assuming you are trying to access /login or /register route from browser search bar something like this http://host:port/login. With this browser will send GET /login request but /login is a POST method route that is the reason you are getting Route not found
When you send request from your browser then by default it will send GET request and your app is not handling GET requests.
You are handling POST requests for /register and /login routes.

req.body is empty in post api (only in my laptop)

I have created this post API, when I am trying to call it from postman req.body is null always, but the same API is working fine on my friend's laptop.
const express = require("express");
const bodyParser = require("body-parser");
const app = express();
app.use(bodyParser.json());
app.use(express.urlencoded({ extended: true}));
const sayHi = (req, res) => {
res.send("Hi!");
};
app.get("/", sayHi);
app.post("/add", (req, res) => {
const { a, b } = req.body;
console.log(req.body)
res.send(`The sum is: ${a + b}`);
});
app.listen(5000, () => {
console.log(`Server is running on port 5000.`);
});
this is my postman request: https://i.stack.imgur.com/d6QAZ.png
update:- I tried the same on my other laptop and it is working fine. I don't know why this is not working in my work laptop.
Hey Once try this middleware and send a proper request from POSTMAN I think this will resolve your all issues..
const express = require("express");
const app = express();
app.use(express.json());
app.use(express.urlencoded({ extended: true}));

Get empty req.body when deployed on Heroku

I have a react app front end posting data to my server(use express) deployed on Heroku. Code works well when both client and server running on localhost, but when it's on Heroku, the req.body always gets empty object {}.
Can anyone point out what's going wrong here? Thanks in advance :)
React code:
axios.post("/api", data, {headers: { "Content-Type": "application/json;charset=utf-8" }})
Express code:
const express = require("express");
const cors = require("cors");
const bodyParser = require("body-parser");
const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(
cors({origin: URL,credentials: true}));
app.post("/api", (req, res) => {const data = req.body; console.log(data);};
This run perfectly on my computer. The log and the response works just fine. Hope it helps. I think the problem could be you are sending a GET request instead of a POST request.
const express = require("express");
const cors = require("cors");
const bodyParser = require("body-parser");
const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cors({origin: new URL('http://localhost:3000'), credentials: true})) // Add this 'new' keyword to URL
app.post("/api", (req, res) => {
const data = req.body
console.log(data)
res.send(data) // Added this to allow request to end
})
// Added this part to start the server listen.
const port = process.env.PORT || 3000
app.listen(port , () => {
console.log('Server is running on port '+3000)
})

Problems POSTing json to Node/Express server from Axios/React

I'm current working on a web application using Node.js with Express in the back-end and React.js in the front end. In attempting to post user data to the Node server, through axios, I am running into an issue. When I make a post with the x-www-form-urlencoded content type, the front end will post to the server but the entire JSON of the posted data appears in the key field of the first element. When I change the content type to json it stops posting anything from the front end. I have tried cUrling to the server, and curling a JSON post will get accepted by the server.
React code to post to server
handleSubmit()
{
var form=this;
var axiosConfig = {
headers: {
'content-type': 'application/json; charset=utf-8'
}
}
axios.post('http://localhost:8080/api/login/', {
'username': form.state.username,
'password': form.state.password
}, {headers: {'content-type': 'application/json'}});
};
Server code for api endpoint
//From server.js
const express=require('express');
const session=require('express-session');
const bodyParser=require("body-parser");
const path = require('path');
var login = require('./routers/login')
var port = process.env.PORT || 8080;
var app=express();
app.use(session({'secret': 'thealphabetbackwardsiszyxwvutsrqponmlkjihgfedcba'}));
app.use(bodyParser.urlencoded({ extended: true}));
app.use(bodyParser.json());
//...
app.use('/api/login', login);
//from login.js
/* Router for login system
When user attempts to log in, check their credentials
If the user successfully logs in, create a session
If user enters invalid credentials prompt them
*/
const path = require('path');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const user = require("./../models/UserSchema")
mongoose.connect('mongodb://localhost/newt');
const express = require('express');
const router = express.Router();
router.get('/', function (req, res)
{
console.log("Test");
})
router.post('/', function(req, res)
{
console.log(req.body);
res.end();
})
// To create test user use path localhost:8080/api/login/testing
router.get('/test', function (req, res)
{
var db = mongoose.connection;
var test = new user({
username: "joesephschomseph",
email: "testUser#test.com",
fname: "Joe",
lname: "Schmoe"
})
test.save();
console.log("Created test user!");
});
module.exports = router
npm install --save const body-parser
in app.js include const bodyparser = require('body-parser');
app.use(bodyparser.urlencoded({ extended: false }));
app.use(bodyparser.json());
remove the single quotes from your 'username' and 'password'
console.log(req.body);

Nodejs app loops continuously and doesnot load the page, as well as cant send post request using postman

I am trying to create an api and send post request using the postman,
but for some reason I'm not getting the data which is sent through the
post man. Instead when I cancel the postman send request I get
response which is shown in the screenshot.
Postman Screenshot:
nodejs server response screenshot:
server.js
const express = require('express');
const morgan = require('morgan');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const cors = require('cors');
// importing custom created modules
const config = require('./config');
// Instantiating express
const app = express();
// Connecting to the mongodbLab
mongoose.connect(config.database, { useNewUrlParser: true }, (error) => {
if (error) {
console.log('Error :',error);
} else {
console.log('Connected to the database.');
}
});
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(morgan('dev'));
app.use(cors);
const userRoutes = require('./routes/account');
app.use('/api/accounts', userRoutes);
// Running the server at port 3000
app.listen(config.port, error => {
console.log('Server started with config file at Port: ' + config.port);
});
account.js
const router = require('express').Router();
const jwt = require('jsonwebtoken'); // Encrypts user data.
router.post('/signup', (req, res, next) => {
console.log(req.body);
});
module.exports = router;
I tried even changing from https://localhost:3000 to
http://localhost:3000 as suggested in this post Here
And even tried adding res.end() as suggested here and here.
But nothing is working, If I goto localhost:3000 the server just keeps loading infinitely. Please help!
Okay I got the solution, it was because of app.use(cors). I don't know why but when I commented out this line everything started to work perfectly.
But in the response although I get the json object. But there is an array of Object, which I didn't get.
Here's the response screenshot:
Edit:
I finally got it I didn't call the cors() method properly. It should have been app.use(cors()), but I called it as just app.use(cors) missing paranthesis().
Now Everything is working fine.

Resources