簡體   English   中英

如何使用 Nuxt.js 服務器中間件發出外部 GET 請求

[英]How to make external GET request using Nuxt.js Server Middleware

我正在使用 Nuxt.js v2.15.8 項目,我正在嘗試使用 Nuxt 為自定義 API 端點提供的服務器中間件功能。 https://nuxtjs.org/docs/configuration-glossary/configuration-servermiddleware/#custom-api-endpoint

我要完成的工作:

使用 Nuxt 服務器中間件向第 3 方 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和我的 Nuxt 項目后向http://localhost:3000/api/server-middleware發出 GET 請求。

我是否誤解了這應該如何工作? 服務器中間件是否僅用於內部 api 調用?

對您的共享代碼應用盡可能少的更改為我們提供以下內容

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM