如何通过 Nuxt.js 服务器从 Nuxt.js 客户端发送请求并将响应接收回客户端

     2023-02-23     170

关键词:

【中文标题】如何通过 Nuxt.js 服务器从 Nuxt.js 客户端发送请求并将响应接收回客户端【英文标题】:How to send a request from Nuxt.js client over Nuxt.js server and receive the response back to the client 【发布时间】:2020-03-22 20:31:31 【问题描述】:

我正在开发一个 Vue.js 应用程序,它只有前端(没有服务器)并向不同的 API 发送大量请求。原本很简单的应用程序变得更加复杂。并且某些 API 存在问题,因为浏览器不接受由于 CORS 的响应。这就是我尝试测试的原因,是否可以将应用程序迁移到 Nuxt.js。

我的方法如下(受comment 启发),但我希望,可能有更好的方法通过服务器从客户端发送请求。

pages/test-page.vue

methods: 
  async sendRequest(testData) 
    const response = await axios.post('api', testData)
    // Here can I use the response on the page.
  

nuxt.config.js

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

服务器中间件/postRequestHandler.js

import axios from 'axios'

const configs = require('../store/config.js')

module.exports = function(req, res, next) 
  let body = ''

  req.on('data', (data) => 
    body += data
  )

  req.on('end', async () => 
    if (req.hasOwnProperty('originalUrl') && req.originalUrl === '/api') 
      const parsedBody = JSON.parse(body)

      // Send the request from the server.
      const response = await axios.post(
        configs.state().testUrl,
        body
      )

      req.body = response
    
    next()
  )

middleware/test.js(参见:API: The Context)

export default function(context) 
  // Universal keys
  const  store  = context
  // Server-side
  if (process.server) 
    const  req  = context
    store.body = req.body
  

pages/api.vue

<template>
   body 
</template>
<script>
export default 
  middleware: 'test',
  computed: 
    body() 
      return this.$store.body
    
  

</script>

当用户在“test”页面上进行操作时,会发起“sendRequest()”方法,然后请求“axios.post('api', testData)”会产生响应,其中包含页面“api”的 HTML 代码。然后我可以从 HTML 中提取 JSON“正文”。

我发现最后一步不是最理想的,但我不知道如何只发送 JSON 而不是整个页面。但我想,必须有更好的方法将数据发送给客户端。

【问题讨论】:

【参考方案1】:

有两种可能的解决方案:

    代理(参见:https://nuxtjs.org/faq/http-proxy) API(参见:https://medium.com/@johnryancottam/running-nuxt-in-parallel-with-express-ffbd1feef83c)

广告 1. 代理

代理的配置可以是这样的:

nuxt.config.js

module.exports = 
...
  modules: [
    '@nuxtjs/axios',
    '@nuxtjs/proxy'
  ],
  proxy: 
    '/proxy/packagist-search/': 
      target: 'https://packagist.org',
      pathRewrite: 
        '^/proxy/packagist-search/': '/search.json?q='
      ,
      changeOrigin: true
    
  ,
  ...

通过代理的请求可能如下所示:

axios
  .get('/proxy/packagist-search/' + this.search.phpLibrary.searchPhrase)
  .then((response) => 
    console.log(
      'Could get the values packagist.org',
      response.data
    )
    
  )
  .catch((e) => 
    console.log(
      'Could not get the values from packagist.org',
      e
    )
  )

广告 2. API

在创建新的 Nuxt.js 应用时,选择 Express 作为项目的服务器端框架。

服务器/index.js

...
app.post('/api/confluence', confluence.send)
app.use(nuxt.render)
...

server/confluence.js(简化版)

const axios = require('axios')
const config = require('../nuxt.config.js')

exports.send = function(req, res) 
  let body = ''
  let page = 

  req.on('data', (data) => 
    body += data
  )

  req.on('end', async () => 
    const parsedBody = JSON.parse(body)
    try 
      page = await axios.get(
        config.api.confluence.url.api + ...,
        config.api.confluence.auth
      )
     catch (e) 
      console.log('ERROR: ', e)
    
  

  res.json(
    page
  )

通过 API 的请求可能如下所示:

this.$axios
  .post('api/confluence', postData)
  .then((response) => 
    console.log('Wiki response: ', response.data)
  )
  .catch((e) => 
    console.log('Could not update the wiki page. ', e)
  )

【讨论】:

nuxt.js服务端渲染中如何实现路由的跳转

一、nuxt.js路由跳转1、nuxt-link标签跳转在html标签内使用nuxt-link跳转,相应于超链接a标签,使用方式如下:<nuxt-linkto="/">首页</nuxt-link>2、编程式导航-JS代码内部跳转实际项目中,很多时候都是通过在JS代码内部进行导航的... 查看详情

如何使用 Nuxt.js 从缓存中排除组件?

】如何使用Nuxt.js从缓存中排除组件?【英文标题】:HowtoexcludecomponentfromcachingusingNuxt.js?【发布时间】:2021-08-1411:18:15【问题描述】:我正在尝试在Nuxt.js中使用Vue.jskeep-aliveprop,我正在尝试缓存除一个之外的所有组件,这是我想... 查看详情

nuxt.js服务端渲染实践,从开发到部署

...的问题路由鉴权第一个拦路虎就是登陆时候的鉴权问题,如何把token保存到本地。官方使用express-ses 查看详情

vue + nuxt.js - 如何读取从外部请求接收到的 POST 请求参数

】vue+nuxt.js-如何读取从外部请求接收到的POST请求参数【英文标题】:vue+nuxt.js-HowtoreadPOSTrequestparametersreceivedfromanexternalrequest【发布时间】:2020-04-1603:20:52【问题描述】:我有一个向我的nuxt应用程序提交发布请求的外部表单。我... 查看详情

如何从 auth-module、Nuxt.js 获取 access_token

】如何从auth-module、Nuxt.js获取access_token【英文标题】:HowcanIgetaccess_tokenfromauth-module,Nuxt.js【发布时间】:2019-08-2103:49:26【问题描述】:我尝试使用auth-module以下链接使用Nuxt.js构建Facebook登录。https://github.com/nuxt-community/auth-module我... 查看详情

如何从 nuxt.js 页头的 node_modules 文件夹中引用 js 文件

】如何从nuxt.js页头的node_modules文件夹中引用js文件【英文标题】:HowcanIreferencejsfilefromnode_modulesfolderinpageheadinnuxt.js【发布时间】:2019-09-1703:04:19【问题描述】:我已将包onesignal-emoji-picker添加到我的nuxt.jsvue项目中,我想在我的页... 查看详情

如何使用 Nuxt.js 将数据存储到本地存储

...时间】:2018-05-0602:26:05【问题描述】:如您所知,nuxtjs是服务器端渲染,没有很好的示例如何将数据存储到客户端的本地存储中。我的工作是需要建立登录表单,用户可以将用户名和密码放入表单中,然后将其发送到服务器(通... 查看详情

从 Express 服务器以编程方式构建 Nuxt.js 时出错

】从Express服务器以编程方式构建Nuxt.js时出错【英文标题】:ErrorswhilebuildingNuxt.jsprogrammaticallyfromExpressserver【发布时间】:2019-12-1514:22:03【问题描述】:我正在尝试从我的Express服务器以编程方式运行Nuxt,但在构建应用程序并打开... 查看详情

如何在 Nuxt.js 的 axios 插件中访问当前的 fullPath?

】如何在Nuxt.js的axios插件中访问当前的fullPath?【英文标题】:HowcanIaccessthecurrentfullPathinsideofaaxiosplugininNuxt.js?【发布时间】:2020-02-0807:01:42【问题描述】:我正在尝试从Axios的Nuxt插件中获取通过route.fullPath的当前路径。它在一定... 查看详情

Vue.js 和 Nuxt.js

...麻烦,因为整个nuxt的工作方式之间的可见性为0%。问题:如何注册全局组件。如何在客户端行为的某些用户上切换nuxt中的布局。在哪里编写vue.use(somep 查看详情

如何在 nuxt js 中使用 vuetify 作为插件?

...只读属性“base”我已经从官方codesandbox在线游乐场在本地服务器和共享主机上安装了我的nuxt项目。我一直 查看详情

如何从 nuxt.js 的 assets 文件夹中导入 css 文件

】如何从nuxt.js的assets文件夹中导入css文件【英文标题】:Howtoimportcssfilefromassetsfolderinnuxt.js【发布时间】:2020-06-0208:00:34【问题描述】:<template><divclass="container"><head><linkrel="stylesheet"href="~assets/css/style-light 查看详情

Nuxt.js - 如何将图像上传到 cloudinary?

】Nuxt.js-如何将图像上传到cloudinary?【英文标题】:Nuxt.js-Howtouploadimagetocloudinary?【发布时间】:2021-03-0803:15:23【问题描述】:我正在尝试从客户端将图像上传到cloudinary。我创建了一个表单数据,我正在尝试传递它,但它返回为... 查看详情

如何让 Nuxt.js 预渲染页面的完整 HTML?

】如何让Nuxt.js预渲染页面的完整HTML?【英文标题】:HowdoIgetNuxt.jstopre-renderthefullHTMLforpages?【发布时间】:2020-09-0814:56:48【问题描述】:我有一个基本应用程序(nuxt版本2.12.2),我通过运行npxcreate-nuxt-app并将模式设置为“SPA”。... 查看详情

如何在实际服务中运行 nuxt.js?

】如何在实际服务中运行nuxt.js?【英文标题】:Howtorunnuxt.jsinrealservice?【发布时间】:2017-10-2817:56:32【问题描述】:我在中使用了vue-clivueinitnuxt/expressmyProject和,npm运行开发开发。但是,npm运行构建之后,创建了dist文件。如何在... 查看详情

Nuxt.JS http/2 帮助和建议

...-2013:32:36【问题描述】:我目前正在使用nuxt.js(使用内置服务器)构建应用程序。也就是说,我一直在通过开发运行谷歌灯塔,而在我的一生中,我无法让它为http/2服务。在nuxt.config.js里面我加了:render:http2:push:true,pushAssets:(req,r... 查看详情

nuxt.js - 如何在服务器端为所有客户端缓存 axios 调用

】nuxt.js-如何在服务器端为所有客户端缓存axios调用【英文标题】:nuxt.js-Howtocacheaxioscallatserversideforallclients【发布时间】:2020-05-1915:45:59【问题描述】:我正在使用vue+nuxt.js应用程序,我想知道是否可以为所有客户端缓存axioswebser... 查看详情

nuxt.js + Apollo Client:如何禁用缓存?

】nuxt.js+ApolloClient:如何禁用缓存?【英文标题】:nuxt.js+ApolloClient:Howtodisablecache?【发布时间】:2019-12-1608:10:10【问题描述】:我设法获得了一个运行typescript和apollographql的nuxt.js+nest.js。为了测试graphql是否有效,我使用了来自this... 查看详情