简体   繁体   English

防止nuxt为nuxt SSR webapp执行客户端代码

[英]Prevent nuxt from executing client-side code for a nuxt SSR webapp

I've created a SSR/progressive nuxt project using create-nuxt-app .我已经使用create-nuxt-app创建了一个 SSR/渐进式 nuxt 项目。

I have two pages, each making an HTTP request to a backend API I manage.我有两个页面,每个页面都向我管理的后端 API 发出 HTTP 请求。 This HTTP request is performed from my nuxt page's async asyncData(ctx) method.这个 HTTP 请求是从我的 nuxt 页面的async asyncData(ctx)方法执行的。

When I access any of these pages directly or reload the these pages, these HTTP requests work fine.当我直接访问这些页面中的任何一个或重新加载这些页面时,这些 HTTP 请求工作正常。 Yet when I either click a <nuxt-link :to=" /mypage " /> or hit the back button on my browser:然而,当我点击<nuxt-link :to=" /mypage " />或点击浏览器上的后退按钮时:

  1. An 'Origin' header is added to my HTTP request all of a sudden. 'Origin' 标头突然添加到我的 HTTP 请求中。 I guess this is the browser doing this because my HTTP request is being made from my client-side JavaScript instead of nuxt's node server, right?我猜这是浏览器这样做的原因,因为我的 HTTP 请求是从我的客户端 JavaScript 而不是 nuxt 的节点服务器发出的,对吗?

  2. The HTTP request is performed yet before the request can send a response, the new page is loaded immediately.在请求可以发送响应之前执行 HTTP 请求,新页面会立即加载。 A console error is shown: Access to XMLHttpRequest at 'http://localhost.myapi/foobar' from origin 'http://localhost.mynuxtapp' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.显示控制台错误: Access to XMLHttpRequest at 'http://localhost.myapi/foobar' from origin 'http://localhost.mynuxtapp' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. This kind of makes sense because I set a breakpoint on my API and it doesn't even have a chance to respond with this proper header in the response.这是有道理的,因为我在我的 API 上设置了一个断点,它甚至没有机会在响应中使用这个正确的标头进行响应。

  3. The page displays a nuxt "network error" message after clicking this <nuxt-link /> or going back in my browser due to the error message above.由于上述错误消息,在单击此<nuxt-link />或返回浏览器后,该页面会显示一条 nuxt“网络错误”消息。

So my question is:所以我的问题是:

It appears that nuxt's asyncData method ( https://nuxtjs.org/guide/async-data ) performs client side code execution.看来 nuxt 的asyncData方法( https://nuxtjs.org/guide/async-data )执行客户端代码执行。 Is there a different method available to prevent this?有没有其他方法可以防止这种情况发生?

只需在asyncData方法中添加if (process.server) {} ,如此处所示,即可仅在服务器端执行代码。

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

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