简体   繁体   English

Nuxt.js + Express + Heroku — Axios 请求在生产环境中返回 404,但在开发模式下不在本地主机上 — 有什么解决方案吗?

[英]Nuxt.js + Express + Heroku — Axios requests return 404 in production, but not on localhost in dev mode — any solution?

I've made a cms for blogging using nuxt.js with express for the server.我已经使用nuxt.js 为服务器制作了一个用于博客的cms。 It uses axios to make asyncData requests to the server before loading each page.它使用 axios 在加载每个页面之前向服务器发出 asyncData 请求。

It works fine when I run it locally , but when I deploy the site on heroku the axios requests all return 404.当我在本地运行它时它工作正常,但是当我在 heroku 上部署站点时,axios 请求都返回 404。

My guess is that the axios requests baseURL is wrong somehow, but when I haven't been able to confirm that.我的猜测是 axios 请求 baseURL 不知何故是错误的,但是当我无法确认时。 I've confused myself.我自己搞糊涂了。

I've tried setting the baseURL to the url of the site, I've tried setting it to http://0.0.0.0:8000 , which is mentioned in the nuxt.js docs我试过将 baseURL 设置为网站的 url,我试过将其设置为http://0.0.0.0:8000 ,这在nuxt.js 文档中提到

I've tried including the modeule @nuxtjs/dotenv with require('dotenv').config() at the top of my nuxt.config.js file.我已经尝试在我的 nuxt.config.js 文件的顶部@nuxtjs/dotenv带有require('dotenv').config()的模式@nuxtjs/dotenv

My nuxt.config.js file我的 nuxt.config.js 文件


    module.exports = {
      mode: 'universal',

      head: {
        title:'',
        meta: [
          { charset: 'utf-8' },
          { name: 'viewport', content: 'width=device-width, initial-scale=1' },
          { hid: 'description', name: 'description', content:'' }
        ],
        link: [
          { rel: 'icon', type: 'image/x-icon', href: '/favicon.png' }
        ]
      },

      loading: { color: '#fff' },

      css: [
        { src: '~assets/stylesheets/global.scss', lang: 'scss' }
      ],

      plugins: [
      ],
      /*
      ** Nuxt.js modules
      */
      modules: [
        '@nuxtjs/axios',
        '@nuxtjs/eslint-module'
      ],

      axios: {

      },

      build: {
        /*
        ** You can extend webpack config here
        */
        extend(config, ctx) {
          // Run ESLint on save
          if (ctx.isDev && ctx.isClient) {
            config.module.rules.push({
              enforce: 'pre',
              test: /\.(js|vue)$/,
              loader: 'eslint-loader',
              exclude: /(node_modules)/,

              options : {
                    fix : true,
                    extractCSS : true
                }
            })
          }
        }
      }
    }

my server/index.js file我的服务器/index.js 文件


const express = require('express')
const session = require('express-session')
const consola = require('consola')
const passport = require('passport')
const mongoose = require("mongoose")
const bodyParser = require("body-parser")
const cookieParser = require('cookie-parser')
const morgan = require('morgan')
const { Nuxt, Builder } = require('nuxt')

const app = express()


// Import and Set Nuxt.js options
let config = require('../nuxt.config.js')
config.dev = !(process.env.NODE_ENV === 'production')

//Body Parser / Cookie Parser config
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cookieParser())

app.use(morgan('dev'));

// Expresss Session
app.use(session({
  secret: 'lkasjdlmsdj18ka124jlsdalkjmlakjc',
  resave: false,
  saveUninitialized: false,
  cookie: { maxAge: 60000 }
}))
app.use(passport.initialize())
app.use(passport.session())

mongoose.connect(process.env.MONGODB_URI);

require('./auth_config')(passport)
require('./auth')(app,passport)

//Posts
require('./posts.js')(app, mongoose)


async function start() {

  // Init Nuxt.js
  const nuxt = new Nuxt(config)

  const { host, port } = nuxt.options.server



  // Build only in dev mode
  if (config.dev) {
    const builder = new Builder(nuxt)
    await builder.build()
  } else {
    await nuxt.ready()
  }


  // Give nuxt middleware to express
  app.use(nuxt.render)
  // Listen the server
  app.listen(port, host)
  consola.ready({
    message: `Server listening on http://${host}:${port}`,
    badge: true
  })
}
start()

An example of one of the axios routes that queries the database.查询数据库的 axios 路由之一的示例。

  app.get("/api/posts/latest-post", async (req, res) => {
    try {
              var result = await PostModel.findOne({published:true}).sort({"date.published.iso": -1}).exec();
              res.send(result);
          } catch (error) {
              res.status(500).send(error);
      }
  });

The example here should return the latest post, instead I get an nuxt error message "server error."这里的示例应该返回最新的帖子,而不是我收到一条 nuxt 错误消息“服务器错误”。 The same is true for every route that uses axios to request data from the server.对于每一个使用 axios 向服务器请求数据的路由也是如此。

It works exacltly as expected on local host.它在本地主机上完全按预期工作。

Any help would be really appreciated.任何帮助将非常感激。

You can create a new instance of axios with a custom config, like this: axios.create([config]) ->this is the sample //code starts您可以使用自定义配置创建 axios 的新实例,如下所示: axios.create([config]) -> 这是示例 // 代码开始

const instance = axios.create({
  baseURL: 'https://www.abcdxyz.com/api/',// as you used http://0.0.0.0:8000
  timeout: 1000,
  headers: {'X-Custom-Header': 'foobar'} // if you like to send details else remove it
});

//code ends You can also use Axios inline but I prefer an extra utils folder and then a new file named 'axiosconfig' and just import it... helps in the MVC //代码结束您也可以使用 Axios 内联,但我更喜欢一个额外的 utils 文件夹,然后是一个名为“axiosconfig”的新文件,然后将其导入...有助于 MVC

I hope my answer was helpful to you!希望我的回答对你有帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM