我一直在使用expressjs和api服务器开发我的应用程序,Angular 6 as和api服务器在同一项目结构上像这样
所以这是我的index.js
void foo(int x = 7);
foo(5); // x = 5
foo(); // x = 7
这是我的const express = require('express');
const mongoose = require('mongoose');
const cookieSession = require('cookie-session');
const passport = require('passport');
const bodyParser = require('body-parser');
const keys = require('./config/keys');
require('./models/User');
mongoose.connect(keys.mongoURI);
const app = express();
app.use(bodyParser({limit: '50mb'}));
app.use(bodyParser.json());
app.use(
cookieSession({
maxAge: 30 * 24 * 60 * 60 * 1000,
keys: [keys.cookieKey]
})
);
require('./routes/registerRoutes')(app);
if (process.env.NODE_ENV === 'production') {
// Express wil serve up production assets
// like main.js, main.css
app.use(express.static('client/dist'));
// Express will serve up the index.hml file
// if does not recognize the route
const path = require('path');
app.get('*', (req, res) => {
res.sendFile(path.resolve(__dirname, 'client', 'dist', 'index.html'));
})
}
const PORT = process.env.PORT || 5000;
app.listen(PORT);
registerRoutes.js
它在localhost服务器上工作正常,但当我尝试使用const mongoose = require('mongoose');
const User = mongoose.model('users');
module.exports = (app) => {
app.get('/api/competitors', async (req, res) => {
const users = await User.find().sort({ created: 'desc' });
res.send({
users
});
});
app.post('/api/register', async (req, res) => {
const userObject = req.body;
const user = new User({
firstName: userObject.firstName,
lastName: userObject.lastName,
nickName: userObject.nickName,
});
try {
const newUser = await user.save();
res.send(newUser);
} catch (err) {
res.status(422).send(err);
}
});
};
作为反向代理部署到生产服务器时,这样做。
nginx
在静态网站上工作正常。 但是当我试着打电话时
server {
listen 80;
# server_name drtobias.com;
location / {
root project_name/client/dist;
# index index.html;
try_files $uri $uri/ @express; # instead of 404, proxy back to express using a named location $
expires max;
access_log off;
# source: https://stackoverflow.com/a/15467555/8436941
}
location @express {
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_pass http://myserver_ip_address:5000;
}
}
我得到了Post '/api/register'
这样的错误。
那么如何解决这个问题并使网站正确响应api调用?