nginx 404-页面不存在页面不存在.

qzwqbdag  于 2023-05-06  发布在  Nginx
关注(0)|答案(1)|浏览(255)

我需要在我的nginx/sites-available/default配置上做什么更改,以便它可以找到/API/auth?我是nginx新手。我相信问题出在nginx配置中,用于代理请求到API。下面是我的/nginx/sites-available/default配置:

server {
  listen 80 default_server;
  server_name _;

  # react app & front-end files
  location / {
    root /opt/devParty/client/build;
    try_files $uri /index.html;
  }

  # node api reverse proxy
  location /api {
    root /opt/devParty/routes/api;
    try_files $uri /api/auth.js =404;
    add_header 'Access-ControlAllow-Origin' '*';
    proxy_pass http://localhost:4000/;
     }
   }

以下是EC2 Ubuntu上的文件结构:

devParty/
├── client
│   ├── package-lock.json
│   ├── package.json
│   └── webpack.config.js
├── config
│   ├── db.js
│   └── default.json
├── middleware
│   └── auth.js
├── models
│   ├── Post.js
│   ├── Profile.js
│   └── User.js
├── package-lock.json
├── package.json
├── routes
│   └── api
└── server.js

我的server.js文件:

const { application } = require('express')
const express = require('express')
const app = express()
const PORT = process.env.PORT || 4000
const connectDB = require('./config/db')
const path = require('path')

// Connect Database
connectDB()

// Init Midddleware
// Allows us to get data in req.body on users.js
app.use(express.json({ extended: false }))

// app.get('/', (req, res) => res.send('API Running'))

// Define Routes
app.use('/api/users', require('./routes/api/users'))
app.use('/api/auth', require('./routes/api/auth'))
app.use('/api/profile', require('./routes/api/profile'))
app.use('/api/posts', require('./routes/api/posts'))

// Server status assets in production
if(process.env.NODE_ENV === 'production') {
    // Set static foler
    app.use(express.static('client/build'))

    app.get('*', (req, res) => {
        res.sendFile(path.resolve(__dirname, 'client', 'build', 'index.html')) })
}

app.listen(PORT, () => console.log(`Server started on port ${PORT}`))
o75abkj4

o75abkj41#

根据js文件中的路由配置:

app.use('/api/auth', require('./routes/api/auth'))

路由正在等待/api/auth。但是,nginx配置文件删除了/api前缀。把它改成这样:

location /api {
  root /opt/devParty/routes/api;
  try_files $uri /api/auth.js =404;
  add_header 'Access-ControlAllow-Origin' '*';
  proxy_pass http://localhost:4000; # -> remove trailing slash
}

相关问题