【问题标题】:How to make external GET request using Nuxt.js Server Middleware如何使用 Nuxt.js 服务器中间件发出外部 GET 请求
【发布时间】:2022-10-25 05:10:03
【问题描述】:

我正在使用 Nuxt.js v2.15.8 项目,我正在尝试使用 Nuxt 为自定义 API 端点提供的服务器中间件功能。 https://nuxtjs.org/docs/configuration-glossary/configuration-servermiddleware/#custom-api-endpoint

我要完成的工作:

使用 Nuxt 服务器中间件向 3rd 方 api 发出 GET 请求以检索数据。当我尝试设置它并向 Postman 中的端点发出请求时,出现错误

<!doctype html>
<html data-n-head-ssr lang="en" data-n-head="%7B%22lang%22:%7B%22ssr%22:%22en%22%7D%7D">

<head>
    <title>This page could not be found</title> etc....

如何使用 Nuxt 服务器中间件对外部 api 进行 api 调用?

Nuxt.config.js

  serverMiddleware: [
    {
      path: '/api/server-middleware',
      handler: '~/api/getData.js',
    },
  ],

~/api/getData.js

const bodyParser = require('body-parser');
const app = require('express')();

app.use(bodyParser.json());

app.all('https://jsonplaceholder.typicode.com/todos/1', (req, res) => {
  res.json({ data: res.data });
});

module.exports = app;

在 Postman 中,我尝试在运行 npm run dev 之后向 http://localhost:3000/api/server-middleware 发出 GET 请求,并且我的 Nuxt 项目正在运行。

我是否误解了这应该如何工作?服务器中间件是否仅用于内部 api 调用?

【问题讨论】:

    标签: node.js vue.js nuxt.js


    【解决方案1】:

    对您的共享代码应用尽可能少的更改为我们提供以下内容

    getData.js

    import axios from 'axios'
    const app = require('express')()
    
    app.all('/jsonplaceholder/:id', async (req, res) => {
      const { data } = await axios(
        `https://jsonplaceholder.typicode.com/todos/${req.params.id}`
      )
      res.json({ ...data })
    })
    
    module.exports = app
    

    /pages/index.vue

    <template>
      <div>
        <input id="name" v-model="todoId" type="text" name="name" />
        <button @click="callNuxtApi">try local Nuxt API</button>
        <div>
          Response from the backend:
          <pre>{{ response }}</pre>
        </div>
      </div>
    </template>
    
    <script>
    export default {
      name: 'JsonPlaceholderPage',
      data() {
        return {
          todoId: 1,
          response: {},
        }
      },
      methods: {
        async callNuxtApi() {
          const response = await this.$axios.$get(`/api/server-middleware/jsonplaceholder/${this.todoId}`)
          console.log('response', response)
          this.response = response
        },
      },
    }
    </script>
    

    正如你所看到的,/jsonplaceholder/:id 是更合理的,因为它已经以/api/server-middleware/ 为前缀。
    在路径中包含https:// 对浏览器整体来说并不是很好。

    PS:您需要安装axiosexpress 才能工作。 @nuxtjs/axios 在这里不起作用。


    这个答案在这里加入了我的另一个答案:https://stackoverflow.com/a/72102209/8816585

    【讨论】:

    • 我想我的问题是,如果我可以直接从任何 vue 组件对 json 占位符进行 api 调用,那么设置服务器中间件的目的是什么? nuxt服务器中间件解决了什么问题?谢谢!
    • @CodeConnoisseur 它在后端(Node.js 部分)上进行调用,因此它可以避免一些 CORS 问题,使用一些私有令牌,使用一些非浏览器 API 等......你的问题更多的是:“有什么区别在客户端与服务器端 HTTP 调用之间”。因此,它解决了这个特定的用例。在你的例子中可能完全不值得。
    • 这是有道理的,所以在我对端点进行 REST 调用的情况下,该端点需要我发送不记名令牌而不暴露给客户端,在这种情况下,我想使用 nuxt 服务器中间件......对吗?
    • @CodeConnoisseur 你可以这样做,是的,就像explained here 一样,但是使用 Nuxt2 有点棘手(使用 Nuxt3 更简单)。您还可以使用中间件后端(位于其他地方)或无服务器功能来完成仍然需要隐藏一些私有令牌的简单快速的任务。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-07-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-27
    • 1970-01-01
    相关资源
    最近更新 更多