Node js Rest API 不工作 - 共享主机服务器 - Plesk
Node js Rest API not working - Shared Hosting Server - Plesk
Node js Rest API 在产品服务器中不工作。它在本地工作正常。
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);
});
}
获取:http://api.**********.xyz/ 正在本地和生产服务器中工作
get: http://api.*******.xyz/api/auth/ 正在本地和生产服务器中工作
Post: http://api.*******.xyz/api/auth/signin 在本地工作,在产品服务器中不工作(Plesk 服务器)。所有 post 和 put 方法在生产服务器中都不起作用,但在本地工作正常
在您的 signup
post 请求中,您正在使用中间件作为 array
,请删除 third parenthesis
并重试。
您的注册路径应该是,
router.post('/signup', verifySignUp.checkDuplicateUserNameOrEmail, controller.signup);
如果你正在看Maximillian课程,你可以重新检查app模块的路径
var app = require('./app');
我觉得应该是
var app = require('./backend/app');
不知道,如果你已经有了答案,但我遇到了同样的问题。
修复方法是设置 Websites & Domains -> Hosting Settings -> Preferred domain
。
已设置为 "www.domain.xy"
。
我将不带 "www"
的域 "domain.xy"
设置为首选。
问题是,nginx 使用重定向 301 将请求从“domain.xy”重定向到“www.domain.xy”。然后 POST 变成 GET 请求。
此更改后不再执行重定向,我收到了 POST 请求。
Node js Rest API 在产品服务器中不工作。它在本地工作正常。
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);
});
}
获取:http://api.**********.xyz/ 正在本地和生产服务器中工作
get: http://api.*******.xyz/api/auth/ 正在本地和生产服务器中工作
Post: http://api.*******.xyz/api/auth/signin 在本地工作,在产品服务器中不工作(Plesk 服务器)。所有 post 和 put 方法在生产服务器中都不起作用,但在本地工作正常
在您的 signup
post 请求中,您正在使用中间件作为 array
,请删除 third parenthesis
并重试。
您的注册路径应该是,
router.post('/signup', verifySignUp.checkDuplicateUserNameOrEmail, controller.signup);
如果你正在看Maximillian课程,你可以重新检查app模块的路径
var app = require('./app');
我觉得应该是
var app = require('./backend/app');
不知道,如果你已经有了答案,但我遇到了同样的问题。
修复方法是设置 Websites & Domains -> Hosting Settings -> Preferred domain
。
已设置为 "www.domain.xy"
。
我将不带 "www"
的域 "domain.xy"
设置为首选。
问题是,nginx 使用重定向 301 将请求从“domain.xy”重定向到“www.domain.xy”。然后 POST 变成 GET 请求。
此更改后不再执行重定向,我收到了 POST 请求。