Express Post Request 404 - javascript

I'll try to make this as to the point as possible. I am trying to make a post request to my express backend. All of the post requests here work, except for "/addpayment". Here is my file called 'router.js'
module.exports = function(app) {
app.post('/signin', requireSignin, Authentication.signin)
app.post('/signup', Authentication.signup)
app.post('/addpayment', function(req, res, next) {
res.send({ message: 'why................' })
})
}
Here is my main 'server.js' file
const express = require('express')
const http = require('http')
const bodyParser = require('body-parser')
const morgan = require('morgan')
const app = express()
const router = require('./router')
const mongoose = require('mongoose')
const cors = require('cors')
// DB Connect
mongoose.connect('mongodb://localhost/demo-app')
// App
app.use(morgan('combined'))
app.use(cors())
app.use(bodyParser.json({ type: '*/*' }))
router(app)
// Server
const port = process.env.PORT || 3090
const server = http.createServer(app)
server.listen(port)
console.log('Server has been started, and is listening on port: ' + port)
I get a 404 in postman, and inside my app browser console. I am using passport in my other routes. I already tried running it through passport when I have a JWT token, and same thing(a 404).
I have already looked at all Stack Overflow/Github posts on the first few pages of google results, with no solution for my use case.

I have made a simplified version of your server and everything works as expected. Only difference that I have made is that I am not creating http server like you, but just calling app.listen
here is working example
router.js
module.exports = function(app) {
app.post('/addpayment', function(req, res, next) {
res.send({message: 'why................'})
})
};
server.js
var express = require('express');
var router = require('./router');
var app = express();
router(app);
//init server
app.listen(3000, function() {
console.log("Server running on port 3000");
});

Related

Node.js Express GET request does not work even though the same request with POST works fine

GET request return 404 error but POST request to the same url works fine I could not figure out the reason.
this is the server setup:
images.route.js
const express= require('express');
const controllers = require('./controllers');
const router= express.Router();
const upload = require('../../lib/uploads.controller');
router.get('/', (req, res)=> res.send('get request'))
router.post('/', controllers.getAll);
module.exports= router;
route.js
const express = require('express'),
router = express.Router();
const albumRoutes = require('./albums/album.route');
const imageRoutes= require('./images/index');
router.use('/albums', albumRoutes);
router.use('/images', imageRoutes);
module.exports= router;
server.js
let express = require('express'),
cors = require('cors'),
bodyParser = require('body-parser');
let history = require('connect-history-api-fallback');
const userRoute = require('./routes/router');
const app = express();
app.options('*', cors())
app.use(cors());
app.use(history());
app.use(express.json({limit:
'50mb'}));
app.use(express.urlencoded({
extended: true,
limit: '50mb',
parameterLimit: 1000000
}));
app.use('/api', userRoute)
const port = process.env.PORT || 4000;
app.listen(port, () => {
console.log('Connected to port ' + port)
})
I have been searching for a solution but I could not find any reason.
I even installed different REST API apps like postman and insomnia just in case, but it is the same

Curl is allowing POST requests but browser is not

I am trying to develop an API that allow POST request of file data, but the POST request only functions using curl curl -X POST --data file= mouse.fa "http://localhost:3000/api/data?file=mouse.fa" . When I trying a POST request in the browser, I get a GET error Cannot GET /api/data. Please could you advise me on how to get the POST request to work in the browser in addition to curl.
router.js
const fs = require('fs');
const express = require('express');
const bodyParser = require('body-parser');
fileParser = require("./fileParser")
router.use('./fileParser', fileParser.parse);
// middleware
router.use(function (req, res, next) {
console.log('Received request');
next();
});
router.post('/data', function (req, res) {
//Check file is valid
if (!req.body.file.toString().endsWith('.fa')) {
res.status(400).json({ message: "Bad Request" });
} else {
fileParser.parse(`./${req.body.file.toString()}`);
res.json({ message: "File parsed and data submitted.", location: "/data/" });
}
});
server.js
const express = require('express');
// create server
const app = express();
const port = 3000;
app.listen(port, function () {
console.log(`Server running at ${port}`)
});
// import router
const router = require('./router');
app.use('/api', router)

how to solve Express.js 404 status?

I'm quite new for node.js and express.js.
I'm trying to create a login form using MERN.
when I try to access register route I always jumping to 404 status I don't understand what's wrong with my code please help me on this. I'm following this youtube tutorial -- https://www.youtube.com/watch?v=y7yFXKsMD_U&t=35s
testing these codes using POSTMAN please refer below screenshot.
[![enter image description here][1]][1]
server.js | File
const express = require("express");
const morgon = require("morgan");
const bodyParser = require("body-parser");
const cors = require("cors");
const app = express();
require("dotenv").config({
path: "./config/config.env",
});
app.use(bodyParser.json());
if (process.env.NODE_ENV === "development") {
app.use(
cors({
origin: process.env.CLIENT_URL
})
);
app.use(morgon("dev"));
}
// Load all routes
const authRouter = require("./routers/auth.route");
// use routes
app.use("/api/", authRouter);
app.use((req, res, next) => {
res.status(404).json({
success: false,
message: "Page Not Founded",
});
});
const PORT = process.env.PORT;
app.listen(PORT, () => {
console.log(`App PORT up on port ${PORT}`);
});
config.env | File
PORT = 5000
NODE_ENV = development
CLIENT_URL = http://localhost:3000
auth.route.js | Route File
const express = require("express");
const router = express.Router();
// Load register Controller
const { registerController } = require("../controller/auth.controller.js");
// register Router path
router.post("register", registerController);
module.exports = router;
auth.controller.js | Controller File
exports.registerController = (req, res) => {
const {name, email, password} = req.body
console.log(name, email, password)
}
In your router path, you need a / in your register route.
router.post("/register", registerController);
You also do not need a trailing slash in your API route.
app.use("/api", authRouter);

Get method not able to be detected by the Node.js

I am new to node and express js.Today I am learning and I have initialized node server as:
const express = require('express')
const bodyParser = require('body-parser')
const cors = require('cors')
const PORT = 3000
const api=require('./routes/api')
const app = express()
app.use(bodyParser.json())
app.use(cors())
api.use('/api',api)
app.get('/', function(req, res) {
res.send('Hello from server')
})
app.listen(PORT, function(){
console.log("Server running on localhost:" + PORT)
});
I have created a folder routes inside server folder and there is api.js file which has GET method to test, whether the api is working or not.Inside api.js I have,
const express = require('express')
const router=express.Router()
router.get('/', (req, res) => {
res.send('from Api Route');
})
module.exports=router
I type node server and it is displaying me :
Server running on localhost:3000
But,when I try to get the url: http://localhost:3000/api,it is displaying me:
And,in api.js file in the arrow function sublime is showing me error in red marker as:
Replace api.use('/api',api) with app.use('/api',api)

Node.js and Express relationship

I'm trying to understand the connection between Node.js and Express.
My Code for creating a Node.js Server:
const https = require('https');
const fs = require('fs');
const options = {
key: fs.readFileSync('./https1/key.pem'),
cert: fs.readFileSync('./https1/cert.pem')
};
const server = https.createServer(options, function(req,res){
res.writeHead(200);
res.end(`Hello world!!!!!!!!!!! \n`);
});
server.listen(3000, function(){
console.log('Server listening on port 3000 \n');
});
I run a curl operation curl -k localhost:3000 and it gives me a "Hello World" Output
My code for creating an Express Server:
// call the packages we need
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
var port = process.env.PORT || 8080;
// ROUTES FOR OUR API
var router = express.Router();
// test route to make sure everything is working (accessed at GET http://localhost:8080/api)
router.get('/', function(req, res) {
res.json({ message: 'hooray! welcome to our api!' });
});
app.listen(port);
console.log('Magic happens on port ' + port);
Is it possible for us to mix both of these?
To be more specific, I would like to create my Server using the Node.js way, but create my routes using the Express way. Can I do it or should I just follow one methodology? What is the connection between Node.js and Express? I understand that Express is just a framework for Node.js but where exactly does the deviation occurs if at all any?
Can I mix and combine the two when required?
Thank you
Yes you can combine nodejs and express, but not encourage you to combine those unless you have specific purpose such as using AWS lambda or making specific OS tasks that has to be made only with pure node.
As you already know, express is just a framework. You can write code more shortly using express.
For example, to make the browser displaying Hello world,
// nodejs version
const http = require('http');
const hostname = '127.0.0.1';
const port = 3000;
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('Hello World!\n');
});
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
// express version
const express = require('express');
const app = express();
const port = 3000;
app.listen(port, (req, res) => {
res.send('Hello World!\n');
})
More easier, and intuitive.
You surely can that's the way to create a Secure HTTPS server with express and followed in most projects
const https = require('https');
const express = require('express');
const app = express();
const options = {
key: fs.readFileSync('./https1/key.pem'),
cert: fs.readFileSync('./https1/cert.pem')
};
const server = https.createServer(options, app);
app.get('/', (req, res) => {
res.send('hello world')
}
server.listen(config.port, () => {
console.log(`Express server listening on port ${port} in ${app.get('env')} mode`);
});
Now add your routes and all.

Categories

Resources