简体   繁体   English

如何使用 Nuxt.js 服务器中间件发出外部 GET 请求

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

I am working with a Nuxt.js v2.15.8 project and I am attempting to use the server middleware feature that Nuxt offers for A custom API endpoint.我正在使用 Nuxt.js v2.15.8 项目,我正在尝试使用 Nuxt 为自定义 API 端点提供的服务器中间件功能。 https://nuxtjs.org/docs/configuration-glossary/configuration-servermiddleware/#custom-api-endpoint https://nuxtjs.org/docs/configuration-glossary/configuration-servermiddleware/#custom-api-endpoint

What I am trying to accomplish:我要完成的工作:

Use Nuxt server middleware to make a GET request to a 3rd party api to retrieve data.使用 Nuxt 服务器中间件向第 3 方 api 发出 GET 请求以检索数据。 When I try to set this up and make the request to the endpoint in Postman, I get an error当我尝试设置它并向 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....

How do I use the Nuxt server middleware to make api calls to external api's?如何使用 Nuxt 服务器中间件对外部 api 进行 api 调用?

Nuxt.config.js Nuxt.config.js

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

~/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;

In Postman I try to make a GET request to http://localhost:3000/api/server-middleware after running npm run dev and my Nuxt project is running.在 Postman 中,我尝试在运行npm run dev和我的 Nuxt 项目后向http://localhost:3000/api/server-middleware发出 GET 请求。

Am I misunderstanding how this is supposed to work?我是否误解了这应该如何工作? Is the Server Middleware for internal api calls only?服务器中间件是否仅用于内部 api 调用?

Applying the least possible amount of changes to your shared code gives us the following对您的共享代码应用尽可能少的更改为我们提供以下内容

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>

As you can see, /jsonplaceholder/:id is something more reasonable considering that it will be prefixed by /api/server-middleware/ already.正如你所看到的, /jsonplaceholder/:id是更合理的,因为它已经以/api/server-middleware/为前缀。
Having https:// inside of a path is not really nice to the browser overall.在路径中https://对浏览器整体来说并不是很好。

PS: you need to install axios and express for it to work. PS:您需要安装axiosexpress它才能工作。 @nuxtjs/axios will not work here. @nuxtjs/axios在这里不起作用。


This answer joins my other one here: https://stackoverflow.com/a/72102209/8816585这个答案在这里加入了我的另一个答案: https://stackoverflow.com/a/72102209/8816585

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

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