网络选项卡中的CORS错误和秘密键
我正在研究Vue Storefront Project(nuxt.js
前端,express.js
back-end)。
我从前端发送信息,然后在Express.js服务器中收到。信息跟踪的路径是home.vue
file-> nuxt plugin.js
文件 - >以及应用程序的express.js
侧面的中间件文件。 (所有这些文件都在一个和同一项目中)。
中间软件将使用Axios进行外部API的要求。然后,信息将返回前端,以供用户看到。
问题是我有一个CORS问题,很可能是因为API不接受我的域而引起的,因此将Cors-Error扔到了选项重新要求之后,从不发送帖子。 问题是我在nuxt.config.js
中启用了服务器端渲染,我的应用程序和API在同一服务器上。 但是我仍然得到了Cors-Error。最重要的是,可以在“网络”选项卡中看到所有秘密键,我认为这很奇怪,因为我已经在服务器上托管了我的应用程序,并且在`nuxt.config.js中都设置了以下设置
export default () => {
const baseConfig = {
ssr: true, // default value is true
target: 'server', // default is 'server'
...
:密钥来自服务器上的环境变量,而不是托管.env
文件。
如何隐藏这些秘密键,并可能修复CORS错误?
CORS错误: 从'api.com'
'MyHostedApp.com'访问xmlhttprequest''已被CORS策略阻止:响应前飞行请求未通过访问控制检查:否请求的资源上存在“访问控制”标头。
CORS浏览器扩展程序的CORS错误: 从'api.com'
'MyHostedApp.com'访问xmlhttprequest''myhostedapp.com'已被CORS策略阻止:响应前飞行请求不会传递访问控制检查:它没有HTTP确定状态。
我的中间件中的Axios请求:
var authBodyFormData = new FormData();
authBodyFormData.append("required_Data", process.env.SAMPLE_ENV_VAR);
async function getAuthtoken() {
try {
const res = await axios({
method: "post",
headers: {
'Access-Control-Allow-Origin': '*',
"Content-Type": "application/x-www-form-urlencoded"
},
url: process.env.AUTH_URL,
data: authBodyFormData,
});
return response?.data ?? undefined;
} catch (e) {
console.warn(e);
}
}
浏览器请求:
**General:**
Request URL: API.com
Referrer Policy: strict-origin-when-cross-origin
**Request Headers:**
Provisional headers are shown Learn more
Accept: application/json, text/plain, */*
Access-Control-Allow-Origin: *
Content-Type: multipart/form-data; boundary=----WebKitFormBoundary8fuAlA3VfBtdUPym
Referer: MyhostedApp.com
sec-ch-ua: " Not A;Brand";v="99", "Chromium";v="101", "Google Chrome";v="101"
sec-ch-ua-mobile: ?0
sec-ch-ua-platform: "Windows"
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/101.0.4951.67 Safari/537.36
I'm working on Vue Storefront project(Nuxt.js
front-end, Express.js
back-end).
I send information from my front-end which I then receive in the Express.js server. The path the information follows is a Home.vue
file --> a Nuxt Plugin.js
file --> and the a middleware file which is on the Express.js
side of the app. (all these files are inside one and the same project).
The middleware will do a POST-request to an external API using Axios. The information will then return to the front-end for the user to be seen.
The problem is that I have an CORS issue, which will most likely be caused because the API does not accept my domain and thus throws the CORS-error at the OPTIONS-request, never sending the POST after that.
The thing is that I have Server Side Rendering enabled in the nuxt.config.js
, my app and the API are on the same server.
But still I get the CORS-error. On top of that, all the Secret keys can be seen in the network tab, which I think is weird because I have hosted my app on my server, and in `nuxt.config.js I've set the following settings:
export default () => {
const baseConfig = {
ssr: true, // default value is true
target: 'server', // default is 'server'
...
The these keys come from Environment Variables on the server, not from a hosted .env
file.
How can I hide these Secret keys, and possibly fix the CORS error?
CORS error:
Access to XMLHttpRequest at 'API.com'
from origin 'MyhostedApp.com'
has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
CORS error with CORS-browser extension:
Access to XMLHttpRequest at 'API.com'
from origin 'MyhostedApp.com'
has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.
Axios request in my Middleware:
var authBodyFormData = new FormData();
authBodyFormData.append("required_Data", process.env.SAMPLE_ENV_VAR);
async function getAuthtoken() {
try {
const res = await axios({
method: "post",
headers: {
'Access-Control-Allow-Origin': '*',
"Content-Type": "application/x-www-form-urlencoded"
},
url: process.env.AUTH_URL,
data: authBodyFormData,
});
return response?.data ?? undefined;
} catch (e) {
console.warn(e);
}
}
Browsers request:
**General:**
Request URL: API.com
Referrer Policy: strict-origin-when-cross-origin
**Request Headers:**
Provisional headers are shown Learn more
Accept: application/json, text/plain, */*
Access-Control-Allow-Origin: *
Content-Type: multipart/form-data; boundary=----WebKitFormBoundary8fuAlA3VfBtdUPym
Referer: MyhostedApp.com
sec-ch-ua: " Not A;Brand";v="99", "Chromium";v="101", "Google Chrome";v="101"
sec-ch-ua-mobile: ?0
sec-ch-ua-platform: "Windows"
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/101.0.4951.67 Safari/537.36
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
CORS与您的NUXT配置完全无关,更多详细信息可在此处提供。
TDLR:将其修复在您的后端(上面的给定链接中有几个答案)。
NUXT是带有某些SSR或SSG的类固醇的VUE应用。它不应替换快车或同样的服务器。另外,要理解的一件重要的事情是,ENV变量可用,但仅在服务器上可用(例如初始渲染或构建/生成应用程序时)。
target
和ssr
的值在这里完全无关紧要,因为这是后端配置问题。初始渲染后,您的NUXT应用程序的表现主要像VUE应用程序,所有后续导航都将是客户端。因此,所有HTTP调用都将公开可用(这是前端应用程序的工作方式)。
如果您想隐藏一些东西(通常不需要真正需要),则可以打电话给后端,后端将通过敏感令牌,因此对真实的后端进行了呼叫,有点像 中间件后端。
这是完全相同的,两者之间没有区别,因为它们基本上是同一件事。
target:'server'
在此处不更改任何内容,因为它与页面生成方式有关,而是“您可以在服务器上拨打所有电话吗?”,例如< a href =“ https://nuxtjs.org/docs/features/deployment-targets#server-hosting” rel =“ nofollow noreferrer”>在这里解释了。另外,如果您在同一位置将NUXT应用程序和API放在同一位置,则需要在同一主机上循环返回CORS。
如果您在
yolo.com
上拥有API,并且NUXT应用程序也位于Yolo.com
,您仍然需要告诉您的Express应用程序,您需要允许来自yolo.com
的任何调用 。CORS is totally unrelated to your Nuxt configuration, more details are available here.
TDLR: fix those on your backend (several answers are available in the given link above).
Nuxt is a Vue app on steroids with some SSR or SSG. It is not supposed to replace an Express server or alike. Also, one important thing to understand is that env variables are available but private ones will only be available on the server (like the initial render or when building/generating the app). The values of
target
andssr
are totally irrelevant here because it's a backend configuration issue anyway.After the initial render, your Nuxt app will behave mostly like a Vue app and all the subsequent navigations will be client-side. Hence, all the HTTP calls will be publicly available (this is how a frontend app works).
If you want to hide some stuff (no real need usually), you could make some calls to a backend who will pass the sensitive tokens and so to the real backend, somewhat like a middleware backend.
This is exactly the same, there is no difference between both because they are basically the same thing.
The
target: 'server'
doesn't change anything here, since it's related to how page generation is made, it's not a "could you make all of the call on the server please?", as explained here.Also, if you have the Nuxt app and the API in the same place, you still need to enable the CORS there since you will loopback on the same host.
If you have your API at
yolo.com
, and the Nuxt app is also located ayolo.com
, you still need to tell to your Express app that you need to allow any calls coming fromyolo.com
to your API endpoint.