从Vue呼叫时的Koa 404

时间:2019-10-25 16:14:59

标签: node.js vue.js axios koa

我正在尝试使用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] }

有人能指出我正确的方向吗?

2 个答案:

答案 0 :(得分:0)

我从未使用Nuxt构建应用程序,但无论如何我都会尽力帮助您。

首先,我建议您阅读有关承诺的内容:
 -https://github.com/leonardomso/You-Dont-Know-JS/blob/master/async%20%26%20performance/ch3.md
 -https://github.com/leonardomso/You-Dont-Know-JS/blob/master/es6%20%26%20beyond/ch8.md
(这是JS好的书籍系列的两章!)

第二,您可以尝试两种方法来查找错误:
 -在您的实体中添加.catch块,以检查是否出现问题;
 -添加仅记录“确定”的虚拟路由,以确保路由已注册并可以响应。

希望这对您有帮助!

答案 1 :(得分:0)

我的nuxt / express.js应用出现此问题: 如果您尝试输入浏览器yourURL/getitems,那么您的nuxt应用程序将尝试将您路由到该页面,而不仅仅是显示数据。

首先要说的是,您需要定义后端应处理的网址。 您转到nuxt.config.js并添加以下代码行:

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

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

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

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

如果一切正常,则您的URL现在应该带有前缀api,并且您应该能够使用localhost:PORT/api/getitems来获取数据

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

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

这是有关serverMiddleware

的更多信息

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

编辑:

在拥有文件夹的某个地方,可以说ist名为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添加到a​​xios URL中,因为这就是您定义的服务器将要处理的路径。