[英]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:您需要安装axios
并express
它才能工作。 @nuxtjs/axios
在这里不起作用。
这个答案在这里加入了我的另一个答案: https://stackoverflow.com/a/72102209/8816585
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.