gpt4 book ai didi

javascript - axios、数组参数和 CORS

转载 作者:行者123 更新时间:2023-12-01 00:12:54 25 4
gpt4 key购买 nike

我正在使用 axios 和 quasar/vue。 axios.post(this.serverUrl, null, {params: {blah: "test"}}params 是第三个参数。我看到它应该是第二,但当它是时,我得到以下结果:

Access to XMLHttpRequest at 'https://example.com' from origin 'http://localhost:8080' 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.

当它是第三个参数时,一切都很好。

一切都很好,直到我需要传递 json 数组,例如: var info = [{name: "test", age: 40},{name: "tester", age: 50}]无论我尝试什么,包括使用 qs:axios.post(this.serverUrl, null, {params: {dataToSend: info},paramsSerializer: params => { return qs.stringify(params)}以及另一种解析方法

parseParams(params) {
const keys = Object.keys(params);
let options = '';
keys.forEach((key) => {
const isParamTypeObject = typeof params[key] === 'object';
const isParamTypeArray = isParamTypeObject && (params[key].length >= 0);
if (!isParamTypeObject) {
options += `${key}=${params[key]}&`;
}
if (isParamTypeObject && isParamTypeArray) {
params[key].forEach((element) => {
options += `${key}=${element}&`;
});
}
});
return options ? options.slice(0, -1) : options;
},

我开始收到上述 CORS 错误。

我的猜测是解析是错误的,但即使在阅读了网络上的大量示例之后,我也不知道如何克服这个问题。我的服务器期望收到像上面这样的 json 数组 [{name: "test", age: 40},{name: "tester", age: 50}]所以我需要客户这样发送它。我正在使用 axios 0.19.1

我错过了什么?谢谢!

更新:

"/api": {
target: "https://myrealdomain.com:8443",
changeOrigin: true,
pathRewrite: {
"^/api": "/mysuffix1/mysuffix2"
}
}

并调用axios.post("api", {...})有效,但在现实生活中,文件将位于与服务器相同的位置 https://myrealdomain.com我不需要API后缀,只需要mysuffix1/mysuffix2。

我可以在开发中模拟changeOrigin,使其与产品一样吗?

最佳答案

如果您计划最终将 Quasar 应用程序部署在与您调用的 API 相同的域名上,则可以在 localhost:8080 上开发期间避免在此 API 服务器上使用 CORS 规则:配置代理规则。当您使用 ...

开发模式下启动 Quasar 时

$ 类星体开发

它启动了 WebPack Dev server 。该服务器可以通过 quasar.config.js 进行配置。开发服务器包含一个代理 API,可以通过从应用程序调用 localhost:8080 来调用,然后将它们转发到 example.com,从而更改 API 中的域名通过此设置请求:changeOrigin: true。现在,您位于 example.com 的 API 服务器会看到似乎来自同一源域的请求,因此不需要 CORS 规则!

devServer: {
// https: true,
port: 8080,
open: true, // opens browser window automatically
// set up one or more proxy rules
proxy: {
// Proxy requests prefixed by /api URL
"/api": {
target: "https://example.com",
changeOrigin: true, // Avoids the need for CORS rule on your API server
// Optionally map /api to the same or a different path on the API server
pathRewrite: {
"^/api": "api"
}
}
}
},

有关更多信息,请参阅...

关于javascript - axios、数组参数和 CORS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59945109/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com