【发布时间】: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 调用?
【问题讨论】: