我在目录“Server”中有 server.js 文件,它与 Nuxt.js 连接
server.js
const express = require('express');
const app = express();
app.get('/api/data', (req, res) => {
res.json({ message: 'Hello from server!' });
});
module.exports = {
path: '/api',
handler: app
};
nuxt.config.ts
export default defineNuxtConfig({
devtools: { enabled: true },
serverMiddleware: [
'~/server/server.js'
]
})
我尝试在 Insomnia 中发送 GET:http://localhost:3000/api/data 并收到:
{
"url": "/api/data",
"statusCode": 404,
"statusMessage": "Page not found: /api/data",
"message": "Page not found: /api/data",
"stack": "",
"data": {
"path": "/api/data"
}
}
您必须将
/api
的请求代理给快递。
例如
有一个 hello-world API,由 Express 提供支持
为您的开发环境添加一个域,例如
example.test
将其注册到您的 nginx 配置中
map $http_upgrade $connection_upgrade {
default upgrade;
'' close;
}
server {
listen 80;
server_name .example.test;
index index.html index.htm index.php;
charset utf-8;
# requests to `/api/` will be proxy to express
proxy_set_header X-Forwarded-For $remote_addr;
location ~* ^/api/ {
proxy_pass http://127.0.0.1:3001;
}
# requests to `/` will be proxy to Nuxt
location / {
proxy_pass http://127.0.0.1:3000;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection $connection_upgrade;
proxy_set_header Host $host;
}
}
在您的
host
文件中添加本地域名解析
127.0.0.1 example.test
http://example.test/api/hello-world
const express = require('express')
const app = express()
const port = 3001
app.get('/api/hello-world', (req, res) => {
res.send('Hello World!')
})
app.listen(port, () => {
console.log(`Example app listening on port ${port}`)
})
还有一个 Nuxt3 页面
http://example.test/hello-world
/pages/hello-world.vue
<script lang="ts" setup>
const { data } = useFetch('http://example.test/api/hello-world')
</script>
/api
将由
/api
驱动的 express
和由 Nuxt3 驱动的“/api”视为两个不同的项目