问题
Node js Rest API not working in the prod server. it is locally working fine.
server.js
var app = require('./app');
var http = require('http');
var port = normalizePort(process.env.PORT || '3000');
app.set('port', port);
var server = http.createServer(app);
server.listen(port);
server.on('error', onError);
server.on('listening', onListening);
function normalizePort(val) {
var port = parseInt(val, 10);
if (isNaN(port)) {
return val;
}
if (port >= 0) {
return port;
}
return false;
}
function onError(error) {
if (error.syscall !== 'listen') {
throw error;
}
var bind = typeof port === 'string' ? 'Pipe ' + port : 'Port ' + port;
switch (error.code) {
case 'EACCES':
console.error(bind + ' requires elevated privileges');
process.exit(1);
break;
case 'EADDRINUSE':
console.error(bind + ' is already in use');
process.exit(1);
break;
default:
throw error;
}
}
function onListening() {
var addr = server.address();
var bind = typeof addr === 'string' ? 'pipe ' + addr : 'port ' + addr.port;
console.log('Listening on ' + bind);
}
app.js
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
app.use(bodyParser.json())
var cors = require('cors');
app.use(cors());
const db = require('./app/config/db.config.js');
const Role = db.role;
const auth = require('./app/router/auth.routes');
app.get('/', (req, res) => { res.send('Hey app.js!') });
app.use('/api/auth',auth);
module.exports = app;
auth.routes.js
const router = require("express").Router();
const verifySignUp = require('./verifySignUp');
const authJwt = require('./verifyJwtToken');
const controller = require('../controller/auth.controller');
router.get('/', (req, res) => { res.send('Hey this auth.routes.js!') });
router.post('/signup', [verifySignUp.checkDuplicateUserNameOrEmail], controller.signup);
router.post('/signin', controller.signin);
module.exports = router;
auth.controller.js
const db = require('../config/db.config.js');
const config = require('../config/config.js');
const User = db.user;
const Role = db.role;
const Op = db.Sequelize.Op;
var jwt = require('jsonwebtoken');
var bcrypt = require('bcryptjs');
exports.signup = (req, res) => {
// Save User to Database
console.log("Processing func -> SignUp");
User.create({
firstName: req.body.firstName,
lastName: req.body.lastName,
userName: req.body.userName,
email: req.body.email,
passWord: bcrypt.hashSync(req.body.passWord, 8),
phone: req.body.phone
}).then(user => {
Role.findAll({
where: {
name: {
[Op.or]: req.body.roles
}
}
}).then(roles => {
user.setRoles(roles).then(() => {
res.send({ data: "User registered successfully!" });
});
}).catch(err => {
res.status(500).send("Error -> " + err);
});
}).catch(err => {
res.status(500).send("Fail! Error -> " + err);
})
}
exports.signin = (req, res) => {
console.log("Sign-In");
User.findOne({
where: {
userName: req.body.userName
}
}).then(user => {
if (!user) {
return res.status(404).send('User Not Found.');
}
var passwordIsValid = bcrypt.compareSync(req.body.passWord, user.passWord);
if (!passwordIsValid) {
return res.status(401).send({ auth: false, accessToken: null, reason: "Invalid Password!" });
}
var token = jwt.sign({ id: user.id }, config.secret, {
expiresIn: 86400 // expires in 24 hours
});
var authoritie = [];
user.getRoles().then(roles => {
for (let i = 0; i < roles.length; i++) {
authoritie.push(roles[i].name.toUpperCase())
}
res.status(200).send({
auth: true,
accessToken: token,
userId: user.id,
userName: user.userName,
authorities: authoritie
});
}
)
}).catch(err => {
res.status(500).send('Error -> ' + err);
});
}
Get: http://api.**********.xyz/ is working in local and prod server
get: http://api.*******.xyz/api/auth/ is working in local and prod server
Post: http://api.*******.xyz/api/auth/signin is working in local and not working in prod server (Plesk server). All post and put methods not working in prod server but locally working fine
回答1:
In your signup
post request, you are using middleware as array
, Please remove the third parenthesis
and try again.
Your signup route should be,
router.post('/signup', verifySignUp.checkDuplicateUserNameOrEmail, controller.signup);
回答2:
if you are watching Maximillian course ,you could recheck the path of app module
var app = require('./app');
I think it should be
var app = require('./backend/app');
回答3:
Don't know, if you already have an answer, but i had the same problem.
The fix was to set the Websites & Domains -> Hosting Settings -> Preferred domain
.
It was set to "www.domain.xy"
.
I set the domain "domain.xy"
without "www"
as preferred.
The problem was, that nginx redirects the requests from "domain.xy" to "www.domain.xy" with a redirect 301. Then the POST becomes a GET Request.
After this change a redirect wasn't executed anymore and i got my POST Request.
来源:https://stackoverflow.com/questions/60256417/node-js-rest-api-not-working-plesk-hosting-server