首页 > 解决方案 > 从 Vue 调用时出现 Koa 404

问题描述

我正在尝试使用 Koa 和 Nuxt 构建一个应用程序。这就是我所拥有的:

定义要从 Firestore 中检索的服务:

    const Firestore = require('@google-cloud/firestore');

    const getItems = () => {

        const db = new Firestore({
            projectId: '*******',
            keyFilename: "******"
        });

        db.collection('items').get()
            .then((snapshot) => {
                return snapshot;
            })
    }

定义它们routes.js

    const Router = require('@koa/router');
    const articleService = require('./services/itemservice');
    const router = new Router();

    router.get('/getitems', async(ctx, next) => {
        ctx.body = articleService.getItems();
    });
    module.exports = router;

添加要从中检索的路线routes.js

    app.use(router.routes());
    app.use(router.allowedMethods());

最后从组件中调用它:

  let articles = axios.get('/getitems')
                  .then(response => {
                    console.log(response);
                  })//.....

我收到此错误:

 response:
   { status: 404,
     statusText: 'Not Found',
     headers:
      { 'content-type': 'text/html; charset=us-ascii',
        server: 'Microsoft-HTTPAPI/2.0',
        date: 'Fri, 25 Oct 2019 16:08:00 GMT',
        connection: 'close',
        'content-length': '315' },
     config:
      { url: '/getarticles',
        method: 'get',
        headers: [Object],
        transformRequest: [Array],
        transformResponse: [Array],
        timeout: 0,
        adapter: [Function: httpAdapter],
        xsrfCookieName: 'XSRF-TOKEN',
        xsrfHeaderName: 'X-XSRF-TOKEN',
        maxContentLength: -1,
        validateStatus: [Function: validateStatus],
        data: undefined },
     request:
      ClientRequest {
        _header:
         'GET /getitems HTTP/1.1\r\nAccept: application/json, text/plain, */*\r\nUser-Agent: axios/0.19.0\r\nHost: localhost\r\nConnection: close\r\n\r\n',
        _onPendingData: [Function: noopPendingOutput],
        agent: [Agent],
        socketPath: undefined,
        timeout: undefined,
        method: 'GET',
        path: '/getitems',
        _ended: true,
        res: [IncomingMessage],
        aborted: undefined,
        timeoutCb: null,
        upgradeOrConnect: false,
        parser: null,
        maxHeadersCount: null,
        _redirectable: [Writable],
        [Symbol(isCorked)]: false,
        [Symbol(outHeadersKey)]: [Object] },
     data:
      '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN""http://www.w3.org/TR/html4/strict.dtd">\r\n<HTML><HEAD><TITLE>Not Found</TITLE>\r\n<META HTTP-EQUIV="Content-Type" Content="text/html; charset=us-ascii"></HEAD>\r\n<BODY><h2>Not Found</h2>\r\n<hr><p>HTTP Error 404. The requested resource is not found.</p>\r\n</BODY></HTML>\r\n' },
  isAxiosError: true,
  toJSON: [Function] }

谁能指出我正确的方向?

标签: node.jsvue.jsaxioskoa

解决方案


我的 nuxt / express.js 应用程序遇到了这个问题:如果您尝试在浏览器中输入内容,那么您yourURL/getitems的 nuxt 应用程序将尝试将您路由到该页面,而不仅仅是向您显示数据。

首先要做的,怎么说,你需要定义你的后端应该处理什么url。你去你的nuxt.config.js并添加这行代码:

serverMiddleware: ["~/api/index.js"],

这意味着您有一个名为的文件夹api,并且在该文件夹中您有一个index.js文件,那就是您的 express.js / koa 应用程序。

现在,在index.js您的 express.js / koa 应用程序所在的位置,您需要在行尾添加以下代码:

module.exports = {
   path: "/api",
   handler: app
};

如果一切正常,您的 URL 现在应该有一个前缀api,并且您应该能够使用localhost:PORT/api/getitems

现在 nuxt 不会尝试将您路由到您的url/api,因为它现在知道这是您的后端

如果您可以向我提供您的 nuxt 应用程序的文件夹结构,我可以为您提供更多帮助。

这里有更多关于serverMiddleware

https://nuxtjs.org/api/configuration-servermiddleware

编辑:

某处你有一个文件夹,可以说是命名serverapi

在那个文件夹中应该有一个index.js文件和你的路由、模型、控制器等。

假设您有一个名为的文件夹server,并且在该服务器中,您拥有index.js的应该看起来像这样

const Koa = require('koa');
const app = new Koa();
Import routes from "./routes.js"

app.use(routes)

//here you define now your backend path
module.exports = {
   //you can use any path you want
   path: "/backend",
   handler: app
};
app.listen(3000);

现在您需要转到您的nuxt.config.js文件并指向该index.js文件

 serverMiddleware: ["~/server/index.js"]

现在您可以使用 axios 访问您的数据:

 axios.get("/backend/getitems").then(data => { console.log(data) })

您将需要添加backend到您的 axios url,因为那是您定义的服务器将处理的路径。


推荐阅读