I am testing a user registration route but its returning a Cannot POST /api/user and it seems i can't pin point the problems.
when I run a get request using postman, it works...but when I post, it returns a Cannot POST /api/user result .
Any sort of help/response will be greatly appreciated.
here is my server.js file.
const express = require('express');
const mongosse = require('mongoose');
const bodyParser = require('body-parser');
//const entries = require('./routes/api/entries');
const app = express();
const path = require("path")
//app.use(bodyParser.json());
app.use(express.json())
//const db = require('./config/keys.js').mongoURI;
mongosse
.connect('mongodb+srv://user:pass2i8y7#gytay.qpgpm.mongodb.net/myFirstDatabase?retryWrites=true&w=majority',
{
useUnifiedTopology: true,
useNewUrlParser: true,
useCreateIndex:true
})
.then(() => console.log('its connected'))
.catch(err => console.log(err));
app.use('/api/entries', require('./routes/api/entries'));
app.use('/api/user', require('./routes/api/user'));
//serve a static dish of data
if (process.env.NODE_ENV == 'production') {
//set static folder
app.use(express.static('client/build'));
app.get('*', (req, res) => {
res.sendFile(path.resolve(__dirname,
'client', 'build', 'index.html'));
});
}
const port = process.env.PORT || 5000;
app.listen(port, () => console.log(`Server started on port ${port}`));
And here is my User route.
const express = require('express');
const router__ = express.Router();
//User model
const User = require('../../models/User');
//#Post api/users
//#desc register user/s
router__.post('/', (req, res) => {
res.send('regesiter__here');
});
module.exports = router__;
I couldn't find any problem with the code so, i ended up restarting the server and it worked! everything good
Related
I create routes on Express js in Next js. When i deployed on hosting and sent request on route i getting error 405, but when i do same on localhost everything all right.
I cant understand that is this?
const express = require('express')
const next = require('next')
const bodyParser = require('body-parser')
const PORT = process.env.PORT || 3000
const dev = process.env.NODE_ENV !== 'production' //true false
const nextApp = next({ dev })
const handle = nextApp.getRequestHandler() //part of next config
nextApp.prepare().then(() => {
const app = express()
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
const apiRoutes = require("./routes");
app.use('/api', apiRoutes)
app.get('*', (req,res) => {
console.log('asdfasdfasdfd')
return handle(req,res)
})
app.listen(PORT, err => {
if (err) throw err;
console.log(`ready at http://localhost:${PORT}`)
})
})
I think your express config has problem.
your express server must be like this:
const express = require('express')
const next = require('next')
const handler = routes.getRequestHandler(app)
const app = next({ dir: '.', dev })
app.prepare().then(() => {
const server = express()
server.post('/api', (req, res) => {
handler(req, res, req.url)
)
server.get('*', (req, res) => {
handler(req, res, req.url)
})
}
check the code for server.get and server.post or other http methods.
Error 405 tells that the method is not allowed.
Vercel can't use custom server with next js
https://github.com/vercel/next.js/discussions/13306
I have a react app that is making a REST to a an express node server.
The express router defines a bunch of rest endpoints.
When I hit the endpoints in the express router using postman, it works fine.
When I hit the endpoint with me react app, it doesn't. I'm seeing 400 error when my react app makes the call using axios.
This is what my index.js looks like:
const express = require("express");
const mongoose = require("mongoose");
const bodyParser = require("body-parser");
const passport = require("passport");
const cors = require("cors");
const app = express();
app.use(bodyParser.urlencoded({ extended: false }));
// server.use(bodyParser.json());
app.use(cors());
// app.options("*", cors());
const UserModel = require("./models/User");
mongoose
.connect(
"mongodb"
)
.then(() => console.log("SUCESSFULLY connected to MongoDB!"))
.catch((error) => console.log(`FAILED tot connect to MongoDB: ${error}`));
require("./auth/localStrategyAuth");
const authRoutes = require("./routes/authRoutes");
app.use("/v1", authRoutes);
// app.post("/", (req, res) => {
// res.send("Hello World!");
// });
// app.post("/v1/signup", (req, res) => {
// console.log("lol");
// });
// app.use(express.json());
const PORT = 5000;
app.listen(PORT, () =>
console.log(`ui-rest listening on port localhost:${PORT}`)
);
user.js
const mongoose = require("mongoose");
const bcrypt = require("bcrypt");
const { Schema } = mongoose;
const UserSchema = new Schema({
email: {
type: String,
required: true,
unique: true,
},
password: {
type: String,
required: true,
},
});
const UserModel = mongoose.model("user", UserSchema);
module.exports = UserModel;
authRoutes.js
const express = require("express");
const passport = require("passport");
const jwt = require("jsonwebtoken");
const JWTstrategy = require("passport-jwt").Strategy;
//We use this to extract the JWT sent by the user
const ExtractJWT = require("passport-jwt").ExtractJwt;
const router = express.Router();
// When the user sends a post request to this route, passport authenticates the user based on the
// middleware created previously
router.post(
"/signup",
passport.authenticate("signup", { session: false }),
async (req, res, next) => {
res.json({
message: "Signup successful",
user: req.user,
});
}
module.exports = router;
localStrategyAuth.js
const passport = require("passport");
const localStrategy = require("passport-local").Strategy;
const UserModel = require("../models/User");
//Create a passport middleware to handle user registration
passport.use(
"signup",
new localStrategy(
{
usernameField: "email",
passwordField: "password",
},
async (email, password, done) => {
try {
// Save the information provided by the user to the the database
const user = await UserModel.create({ email, password });
// Send the user information to the next middleware
return done(null, user);
} catch (error) {
done(error);
}
}
)
);
This is what my express router looks like:
const express = require("express");
const router = express.Router();
router.post(
"/signup",
passport.authenticate("signup", { session: false }),
async (req, res, next) => {
res.json({
message: "Signup successful",
user: req.user,
});
}
);
module.exports = router;
What am I missing? I've set up CORS in the index.js file. I just can't see where I'm going wrong. Why cant my react app hit the express router endpoints.
If I have a normal express endpoint, then my react app is able to hit those endpoints. For example, the endpoint below works fine when my react app hits it.
const express = require("express");
const bodyParser = require("body-parser");
const cors = require("cors");
const app = express();
app.post("/", (req, res) => {
res.send("Hello World!");
});
const PORT = 5000;
app.listen(PORT, () =>
console.log(`listening on port localhost:${PORT}`)
app.post("/someSignup", (req, res) => {
console.log("signup");
});
I've also tried things like with no luck:
const authRoutes = require("./routes/authRoutes");
authRoutes.use(cors());
Here is what my react code looks like when it submits the rest call:
// axios setup
axios.create({
baseURL: "http://localhost:5000",
// headers: {
// "Content-Type": "application/json",
// },
});
// Handle submit
handleSubmit = async (event) => {
event.preventDefault();
const newUserData = {
// firstName: this.state.firstName,
// lastName: this.state.lastName,
email: this.state.email,
password: this.state.password,
};
const result = await axios.post("/v1/signup", newUserData);
console.log(result);
};
Here is a screenshot of headers tab on chrome console
Here is a screenshot of response tab on chrome console
Here is a screenshot of the request
400 means bad request, your problem isn't about with cors.
You didn't setup your api to handle JSON data which react sends, so it can't read your request.body and gives 400-Bad Request.
So you need to add this line:
app.use(bodyParser.json());
Also in the current versions of express, body parser isn't required , it comes with express. So you can use it like this:
app.use(express.json());
The reason it worked with postman is that you sent the data in x-www-form-urlencoded.
you can use check my code for cors error.
const express = require('express');
var mongoose = require('mongoose');
const bodyParser = require('body-parser');
var morgan = require('morgan');
var cors = require('cors')
const app = express();
// CORS Middleware
app.use(cors());
// Logger Middleware
app.use(morgan('dev'));
// Bodyparser Middleware
app.use(bodyParser.json());
const MongoClient = require('mongodb').MongoClient;
const uri = "uri";
const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true });
client.connect(err => {
console.log('MongoDB Connected...')
const collection = client.db("dbname").collection("collectionname");
app.post('/name', (req, res) => {
collection. insertOne({ name: req.body.name })
res.send("data added")
});
});
const port = process.env.PORT || 5000;
app.listen(port, function () {
console.log(`Example app listening on port ${port}`);
});
You need to register the cors middleware into express app.
const express = require("express");
const bodyParser = require("body-parser");
const cors = require("cors");
const app = express();
app.use(cors());
app.post("/", (req, res) => {
res.send("Hello World!");
});
const PORT = 5000;
app.listen(PORT, () => console.log(`listening on port localhost:${PORT}`)
I am trying to serve an angular app using nodejs. But i get this error
"Cannot GET /" in the body of the page. I tried a number of things but still this does not work. do you folks have any suggestion?
const express = require('express')
const app = express()
var cors = require('cors')
const bodyParser = require('body-parser')
const fileUpload = require('express-fileupload')
const couchDb = require('./modules/couchDb')
const db = couchDb.db
const schedules = require('./modules/schedules')
const stations = require('./modules/stations')
const testConfigs = require('./modules/testConfigs')
app.use(cors())
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({extended: true}))
app.use(fileUpload())
app.listen(5000, () => console.log('Listening on port 5000'))
////////////////////////////////////////
// View
////////////////////////////////////////
const viewOptions = { include_docs: true }
app.route('/api/schedules').get((req, res) => {
couchDb.getType('schedule', viewOptions).then(docs => {
res.send(docs)
}).catch(err => {
console.log(err)
res.send({})
})
})
app.route('/api/stations').get((req, res) => {
couchDb.getType('station', viewOptions).then(docs => {
res.send(docs)
}).catch(err => {
console.log(err)
res.send({})
})
})
app.route('/api/tests').get((req, res) => {
couchDb.getType('testConfig', viewOptions).then(docs => {
res.send(docs)
}).catch(err => {
console.log(err)
res.send({})
})
})
you are missing your routes e.g
app.get('/', function (req, res) {
res.send('hello world')
})
or you need to include your all routes through middle ware.
You are getting that error because you are not declaring any endpoints or telling the server to serve anything. It is listening on port 5000, but no responses to any urls have been defined. Here is a piece of example code that will resolve your issue.
const express = require('express')
const app = express()
var cors = require('cors')
const bodyParser = require('body-parser')
const fileUpload = require('express-fileupload')
app.use(cors())
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({extended: true}))
app.use(fileUpload())
// This block will make it so that every path on port 5000 responds with "Hello, World!"
app.get('*', (req, res) => {
res.status(200).send("Hello, World!");
});
app.listen(5000, () => console.log('Listening on port 5000'))
This will make it respond with basic text, if you want to serve an angular application, you will need to look into serving static content from express: https://expressjs.com/en/starter/static-files.html
You have to use a routing middleware and map your modules to the required modules.Also make sure your modules are mounted in router instance.
Something like
const express = require('express')
const app = express()
var cors = require('cors')
const bodyParser = require('body-parser')
const fileUpload = require('express-fileupload')
const couchDb = require('./modules/couchDb')
const db = couchDb.db
const schedules = require('./modules/schedules')
const stations = require('./modules/stations')
const testConfigs = require('./modules/testConfigs')
app.use(cors())
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({extended: true}))
app.use(fileUpload())
//All requests with /schedules will go to './modules/schedules'
app.use('/schedules', schedules);
app.use('/stations', stations);
app.listen(5000, () => console.log('Listening on port 5000'))
your ./modules/station should look like
var express = require('express')
var router = express.Router()
router.get('/', function (req, res) {
res.send('You are in /station')
})
router.get('/new', function (req, res) {
res.send('You are in /station/new')
})
module.exports = router
For more : https://expressjs.com/en/guide/routing.html
This is my index.js file:
const express = require('express');
const mongoose = require('mongoose');
const Post = require('./models/Post');
const keys = require('./config/keys');
const path = require('path');
mongoose.connect(keys.mongoURI);
const app = express();
app.use(express.static(path.join(__dirname, '../react-app/build')));
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname, '../react-app/build',
'index.html'));
});
app.get('/posts', (req, res) => {
Post.find({}, (err, posts) => {
if(err) {
console.log(err);
res.sendStatus(500);
} else {
res.send(posts)
}
})
});
const PORT = process.env.PORT || 5000;
app.listen(PORT, () => console.log(`App listening on port ${PORT}`));
I've builded my react frontend to the location specified in the path.join. However, if I use the app.use(express.static(...)), if I use any path at all, it will always return index.html from my build.
I'd like to see the posts object when I got to '/posts' endpoint, but it doesn't work and I can't get the build serving working without express static.
EDIT:
I tried console logging inside '/' handler, but it logged nothing either. I got everything working when I remove the app.use line entirely. Some tutorials use this approach, why is not working?
So try this:
const express = require('express');
const mongoose = require('mongoose');
const Post = require('./models/Post');
const keys = require('./config/keys');
const path = require('path');
mongoose.connect(keys.mongoURI);
const app = express();
app.use(express.static(path.join(__dirname, '../react-app/build')));
app.get('/posts', (req, res) => {
Post.find({}, (err, posts) => {
if(err) {
console.log(err);
res.sendStatus(500);
} else {
res.send(posts)
}
})
});
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname, '../react-app/build',
'index.html'));
});
const PORT = process.env.PORT || 5000;
app.listen(PORT, () => console.log(`App listening on port ${PORT}`));
Im learning nodejs and I'm creating a server to get the price of cryptocurrencies using a npm called Coin-Ticker. I want to use the data I'm getting in an Angular app but it's not displaying the data in the html. This is my code:
server.js
const express = require('express');
const path = require('path');
const http = require('http');
const bodyParser = require('body-parser');
const coinTicker = require('coin-ticker');
const api = require('./server/routes/api');
const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(express.static(path.join(__dirname, 'dist')));
app.use('/api', api);
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, 'dist/index.html'));
});
const port = process.env.PORT || '3000';
app.set('port', port);
const server = http.createServer(app);
server.listen(port, () => console.log(`API running on localhost:${port}`));
API.JS
const express = require('express');
const router = express.Router();
const coinTicker = require('coin-ticker');
/* GET api listing. */
router.get('/', (req, res) => {
res.send('api works');
});
router.get((req, res) => {
coinTicker('bitfinex', 'BTC_USD')
.then(posts => {
res.status(200).json(posts.data);
})
.catch(error => {
res.status(500).send(error)
});
});
module.exports = router;
Thanks for your help!
It is because coin ticker returns the json in the then so when you are doing res.status(200).json(posts.data); it is returning undefined. just replace that with res.status(200).json(posts) and it should work
Also you can not do router.get((req, res) => {
you need a path before this. I tried this code with
router.get('/convert', (req, res) => { and with the changes above it worked