[英]How to solve flutter web api cors error only with dart code?
It seems like CORS error is well-known issue in the web field.似乎 CORS 错误是 web 领域中的众所周知的问题。 But I tried flutter web for the first time ever and I faced critical error.
但是我第一次尝试了 flutter web 并且遇到了严重错误。
The code below worked well in app version when it was running on iOS device, but when i tested the same code on Chrome with web debugging from beta channel, it encountered CORS error.下面的代码在 iOS 设备上运行时在应用程序版本中运行良好,但是当我在 Chrome 上使用 web 从 beta 通道调试测试相同的代码时,它遇到了 CORS 错误。
Other stackoverflow answers explained how to solve the CORS issue with serverside files of their projects.其他 stackoverflow 答案解释了如何解决他们项目的服务器端文件的 CORS 问题。 But I have totally no idea what is server thing and how to deal with their answers.
但我完全不知道什么是服务器,也不知道如何处理他们的回答。 The error message from Chrome console was below
来自 Chrome 控制台的错误消息如下
[ Access to XMLHttpRequest at 'https://kapi.kakao.com/v1/payment/ready' from origin 'http://localhost:52700' 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. [从来源'http://localhost:52700'访问'https://kapi.kakao.com/v1/payment/ready'的XMLHttpRequest已被CORS策略阻止:对预检请求的响应未通过访问控制检查:请求的资源上不存在“Access-Control-Allow-Origin”header。 ]
]
So, what i want to do is to solve above 'Access-Control-Allow-Origin header' issue ONLY WITH DART CODE.所以,我想做的是仅使用 DART 代码解决上面的“Access-Control-Allow-Origin header”问题。 Code below is what i've tried to solve these issues only with my main.dart.
下面的代码是我试图用我的 main.dart 解决这些问题的代码。
onPressed: () async {
var res =
await http.post('https://kapi.kakao.com/v1/payment/ready', encoding: Encoding.getByName('utf8'), headers: {
'Authorization': 'KakaoAK $_ADMIN_KEY',
HttpHeaders.authorizationHeader: 'KakaoAK $_ADMIN_KEY',
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "POST, GET, OPTIONS, PUT, DELETE, HEAD",
}, body: {
'cid': 'TC0ONETIME',
'partner_order_id': 'partner_order_id',
'partner_user_id': 'partner_user_id',
'item_name': 'cool_beer',
'quantity': '1',
'total_amount': '22222',
'vat_amount': '2222',
'tax_free_amount': '0',
'approval_url': '$_URL/kakaopayment',
'fail_url': '$_URL/kakaopayment',
'cancel_url': '$_URL/kakaopayment'
});
Map<String, dynamic> result = json.decode(res.body);
print(result);
},
Even though i actually had the header "Access-Control-Allow-Origin": "*"
which most other answers recommended, the Chrome console printed same error message.即使我实际上有 header
"Access-Control-Allow-Origin": "*"
大多数其他答案推荐,Chrome 控制台打印相同的错误消息。 Weird thing is that the same code made successful request in mobileApp version.奇怪的是,相同的代码在 mobileApp 版本中发出了成功的请求。 So I think this is only problem with flutter WEB VERSION.
所以我认为这只是 flutter WEB 版本的问题。
Hope somebody can figure it out and suggest only-dart code to resolve the issue in my main.dart:!希望有人能弄清楚并建议仅使用 dart 代码来解决我的 main.dart 中的问题:! Thank you for reading [:
感谢您阅读 [:
1- Go to flutter\bin\cache
and remove a file named: flutter_tools.stamp
1- Go 到
flutter\bin\cache
并删除一个名为: flutter_tools.stamp
的文件
2- Go to flutter\packages\flutter_tools\lib\src\web
and open the file chrome.dart
. 2- Go 到
flutter\packages\flutter_tools\lib\src\web
并打开文件chrome.dart
。
3- Find '--disable-extensions'
3-查找
'--disable-extensions'
4- Add '--disable-web-security'
4-添加
'--disable-web-security'
Using Osman Tuzcu 's answer, I created flutter_cors to make the process easier.使用Osman Tuzcu的回答,我创建了flutter_cors来简化这个过程。
run/compile your Flutter web project using web-renderer.使用 web-renderer 运行/编译您的 Flutter web 项目。 This should solve the issue both locally and remotely:
这应该可以解决本地和远程的问题:
flutter run -d chrome --web-renderer html
flutter build web --web-renderer html
Server side engine like node js or django is really needed to work with flutter web with bunch of external apis.像节点 js 或 django 这样的服务器端引擎确实需要与 flutter web 和一堆外部 API 一起使用。 Actually there's high possibility of same CORS error when we try to use internal api because of the CORS mechanism related to port number difference.
实际上,由于与端口号差异相关的 CORS 机制,当我们尝试使用内部 api 时,很有可能出现相同的 CORS 错误。
There are bunch of steps and answers from SO contributors that recommend to use chrome extensions to avoid CORS errors, but that is actually not cool for users. SO 贡献者有很多步骤和答案,建议使用 chrome 扩展来避免 CORS 错误,但这对用户来说实际上并不酷。 All the users should download the browser extensions to use the single website from us, which wouldn't be there if we used true server engines.
所有用户都应该从我们这里下载浏览器扩展程序以使用单个网站,如果我们使用真正的服务器引擎,就不会出现这种情况。
CORS is from browser as far as i know, so our flutter ios and android apps with same api code don't give those CORS errors. CORS is from browser as far as i know, so our flutter ios and android apps with same api code don't give those CORS errors. First time i encountered this error with flutter web, i believed i can deal with CORS in my app code lines.
我第一次遇到 flutter web 这个错误,我相信我可以在我的应用程序代码行中处理 CORS。 But that is actually not healthy way for users and long term dev plans.
但对于用户和长期开发计划来说,这实际上不是健康的方式。
Hope all flutter web newbies understand that web is quite a wild field for us.希望所有 flutter web 新手都明白 web 对我们来说是一个相当狂野的领域。 Even though i'm also newbie here, i highly recommend all the flutter web devs from 1.22.n stable to learn server side engines like node js.
尽管我在这里也是新手,但我强烈推荐所有来自 1.22.n 稳定版的 flutter web 开发人员来学习节点 js 等服务器端引擎。 It is worth try.
值得一试。
And if u came so far down to this line of my self-answer, here's a simple guide for flutter web with node js.如果你走到我的自我回答这一行,这里有一个简单的指南 flutter web 与节点 js。 Flutter web is on stable channel but all those necessary infra are not fully ready for newbies like me.
Flutter web 处于稳定频道,但所有必要的基础设施还没有为像我这样的新手完全准备好。 So be careful when you first dive into web field, and hope you re-check all the conditions and requirements to find out if you really need web version of your flutter app, and also if you really need to do this work with flutter.
So be careful when you first dive into web field, and hope you re-check all the conditions and requirements to find out if you really need web version of your flutter app, and also if you really need to do this work with flutter. And my answer was yes lol
我的回答是肯定的,哈哈
https://blog.logrocket.com/flutter-web-app-node-js/ https://blog.logrocket.com/flutter-web-app-node-js/
I think disabling web security as suggested will make you jump over the current error for now but when you go for production or testing on other devices the problem will persist because it is just a workaround, the correct solution is from the server side to allow CORS from the requesting domain and allow the needed methods, and credentials if needed.我认为按照建议禁用 web 安全性将使您暂时跳过当前错误,但是当您将 go 用于在其他设备上进行生产或测试时,问题将持续存在,因为这只是一种解决方法,正确的解决方案是从服务器端允许 Z5A124FEFF0B4BDEB7B76C来自请求域并允许所需的方法和凭据(如果需要)。
If you run a Spring Boot server, add "@CrossOrigin" to your Controller or to your service method.如果您运行 Spring 引导服务器,请将“@CrossOrigin”添加到您的 Controller 或您的服务方法中。
@CrossOrigin
@PostMapping(path="/upload")
public @ResponseBody ResponseEntity<Void> upload(@RequestBody Object object) {
// ...
}
I know the question explicitly asked for a solution "with dart code" only, but I was not able to fix the exception with dart code (for example by changing the header).我知道这个问题明确要求解决方案“仅使用 dart 代码”,但我无法使用 dart 代码修复异常(例如通过更改标题)。
https://docs.flutter.dev/development/platform-integration/web-images https://docs.flutter.dev/development/platform-integration/web-images
flutter run -d chrome --web-renderer html
flutter build web --web-renderer html
This official solution worked for me on Chrome only ( Source ).这个官方解决方案仅在 Chrome 上对我有用( Source )。 But I had to run it first every time.
但我每次都必须先运行它。
flutter run -d chrome --web-renderer html
And disabling web security also worked ( Source ).并且禁用 web 安全性也有效(来源)。 But the browsers will show a warning banner.
但浏览器会显示警告横幅。
But In case you are running on a different browser than Chrome ( eg Edge ) and you want to keep 'web security' enabled.但是,如果您在与 Chrome 不同的浏览器(例如 Edge )上运行,并且您希望保持“网络安全”处于启用状态。 You can change the default web renderer in settings in VS Code
您可以在 VS Code 的设置中更改默认的 web 渲染器
File ==> Preferences ==> Settings ==> Enter ' Flutter Web ' in the Search Bar ==> Set the default web renderer to html
File ==> Preferences ==> Settings ==> Enter ' Flutter Web ' in the Search Bar ==> Set the default web renderer to html
I think you may not doing this in right way.我认为你可能没有以正确的方式做到这一点。 The cors headers should be added in HTTP response header while you added them in you reuqest header obviously.
cors 标头应添加到 HTTP 响应 header 中,而您显然将它们添加到 Z099FB3965340DBF31E547 中。
for more information check out the documentation https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS#what_requests_use_cors有关更多信息,请查看文档https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS#what_requests_use_cors
I recommend to use Rexios's answer .我建议使用Rexios 的答案。 His package makes it very convenient to modify the Flutter source code.
他的package使得修改Flutter源代码非常方便。
We use a similar approach as Osman Tuzcu.我们使用与 Osman Tuzcu 类似的方法。 Instead of modifying the Flutter source code, we add the
--disable-web-security
argument in a shell script and just forward all other arguments that were set by Flutter. Instead of modifying the Flutter source code, we add the
--disable-web-security
argument in a shell script and just forward all other arguments that were set by Flutter. It might look overly complicated but it takes just a minute and there is no need to repeat it for every Flutter version.它可能看起来过于复杂,但只需一分钟,无需为每个 Flutter 版本重复。
echo '#!/bin/zsh
# See also https://stackoverflow.com/a/31150244/410996
trap "trap - SIGTERM && kill -- -$$" SIGINT SIGTERM EXIT
set -e ; /Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome --test-type --disable-web-security "$@" ; set +e &
PID=$!
wait $PID
trap - SIGINT SIGTERM EXIT
wait $PID
' > ~/chrome_launcher
chmod 755 ~/chrome_launcher
This adds a chrome_launcher
script to your user folder and marks it executable.这会将
chrome_launcher
脚本添加到您的用户文件夹并将其标记为可执行。
.zshrc
(or .bashrc
etc.): .zshrc
(或.bashrc
等):export CHROME_EXECUTABLE=~/chrome_launcher
If a simple restart does not work, use Invalidate Caches / Restart in Android Studio to force loading of changes.如果简单的重启不起作用,请使用 Android Studio 中的Invalidate Caches / Restart来强制加载更改。
The script also adds the --test-type
flag to suppress the ugly warning about the disabled security features.该脚本还添加了
--test-type
标志来抑制有关已禁用安全功能的丑陋警告。 Be aware that this option might also suppress other error messages!请注意,此选项也可能会抑制其他错误消息! The
CHROME_EXECUTABLE
takes only the path to an executable file it is not possible to set arguments there. CHROME_EXECUTABLE
仅采用可执行文件的路径,无法在此处设置 arguments。 Without trapping exit signals and killing the process group, the Google Chrome instance was not killed when you hit the Stop Button in Android Studio.在没有捕获退出信号并终止进程组的情况下,当您在 Android Studio 中点击停止按钮时,Google Chrome 实例不会被终止。
The disabling web security approaches work well in development, but probably not so well in production.禁用 web 安全方法在开发中运行良好,但在生产中可能不太好。 An approach that worked for me in production dart code involves avoiding the pre-flight CORS check entirely by keeping the web request simple.
在生产 dart 代码中对我有用的方法包括通过保持 web 请求简单来完全避免飞行前 CORS 检查。 In my case this meant changing the request header to contain:
在我的情况下,这意味着将请求 header 更改为包含:
'Content-Type': 'text/plain'
Even though I'm actually sending json, setting it to text/plain avoids the pre-flight CORS check.尽管我实际上发送的是 json,但将其设置为 text/plain 可以避免飞行前的 CORS 检查。 The lambda function I'm calling didn't support pre-flight OPTIONS requests.
我打电话的 lambda function 不支持飞行前 OPTIONS 请求。
Here's some info on other ways to keep a request simple and avoid a pre-flight request以下是有关保持请求简单并避免飞行前请求的其他方法的一些信息
This is a CORS (cross-origin resource sharing) issue and you do not have to delete/modify anything.这是一个 CORS(跨域资源共享)问题,您无需删除/修改任何内容。 You just have to enable the CORS request from your server-side and it will work fine.
您只需从服务器端启用 CORS 请求,它就可以正常工作。
In my case, I have created a server with node.js and express.js, so I just added this middleware function that will run for every request.在我的例子中,我创建了一个带有 node.js 和 express.js 的服务器,所以我刚刚添加了这个中间件 function,它将为每个请求运行。
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Methods", "GET,PUT,PATCH,POST,DELETE");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
And BOOOOM.和 BOOOOM。 I received the data.
我收到了数据。
You just have to look at the settings to enable CORS for your server.您只需查看设置即可为您的服务器启用 CORS。
After hours of testing, the following works perfectly for me.经过数小时的测试,以下内容对我来说非常有效。
Add the following to the PHP file:将以下内容添加到 PHP 文件中:
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST');
header("Access-Control-Allow-Headers: X-Requested-With");
This allow the correct connection with the HTTP GET POST with no issue from flutter for me.这允许与 HTTP GET POST 正确连接,对我来说 flutter 没有问题。
I discovered this in the following discussion:我在以下讨论中发现了这一点:
The below solution is great if you are only communicating with a local NodeJS server.如果您只与本地 NodeJS 服务器通信,则以下解决方案非常棒。
C:\node_project\
C:\node_project\
npm init
in the foldernpm init
in the 文件夹
entry point:
must be app.js
for this example to work entry point:
必须是app.js
才能使此示例正常工作npm install express
in the foldernpm install express
app.js
file in the folderapp.js
文件// init express
const express = require("express");
const app = express();
// set the path to the web build folder
app.use(express.static("C:/Users/your_username/path_to_flutter_app/build/web"));
const PORT = process.env.PORT || 8080;
app.listen(PORT, () => {
console.log(`Server listening on port ${PORT}...`);
});
"C:/Users/your_username/path_to_flutter_app/build/web"
must be changed to the web build folder in your flutter app."C:/Users/your_username/path_to_flutter_app/build/web"
更改为 flutter 应用程序中的 web 构建文件夹。C:/Users/your_username/path_to_flutter_app/
C:/Users/your_username/path_to_flutter_app/
flutter build web
flutter build web
C:\node_project\
C:\node_project\
node app.js
node app.js
http://localhost:8080/
into the browserhttp://localhost:8080/
Note that everytime you change your flutter app's dart code you will need to re-run flutter build web
请注意,每次更改 flutter 应用程序的 dart 代码时,您都需要重新运行
flutter build web
In my case, The problem was in laravel backend code which did not support CORS, So I added the CORS into backend project then it worked successfully in test and live.在我的情况下,问题出在 laravel 后端代码中,它不支持 CORS,所以我将 CORS 添加到后端项目中,然后它在测试和生活中成功运行。
I am getting the same error with php api so i add the php code these lines;我遇到了与 php api 相同的错误,所以我在这些行中添加了 php 代码;
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST');
header("Access-Control-Allow-Headers: X-Requested-With");
The 5th step of Osmans answer should be to add the option Osmans答案的第5步应该是添加选项
'--disable-site-isolation-trials', '--disable-site-isolation-trials',
Only this works for me.只有这对我有用。
Chrome version 106.0.5249.119 Chrome 版本 106.0.5249.119
Hi Your error states about the headers that is not present.您好您的错误说明标题不存在。 So it could be that your server is already setup for cors.
所以可能是您的服务器已经为 cors 设置好了。 My error is as follows.
我的错误如下。 Error: XMLHttpRequest error.
错误:XMLHttpRequest 错误。 C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/_internal/js_dev_runtime/patc h/core_patch.dart 963:28 get current packages/http/src/browser_client.dart 69:22 C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/async/zone.dart 1685:54 runUnary C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/async/future_impl.dart 147:18 handleValue C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/async/future_impl.dart 766:44 handleValueCallback C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/async/future_impl.dart 795:13 _propagateToListeners C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/async/future_impl.dart 557:7 [_complete] C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/async/stream_pipe.dart 61:11 _cancelAndValue C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/async/stream.dart 1530:7 C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/_internal/js_dev_runtime/private/ ddc_runtime/operations.dart 334:14 _checkAndC
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/_internal/js_dev_runtime/patch h/core_patch.dart 963:28 获取当前包/http/src/browser_client。 dart 69:22 C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/async/zone.dart 1685:54 runUnary C:/b/s/w/ir /cache/builder/src/out/host_debug/dart-sdk/lib/async/future_impl.dart 147:18 handleValue C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk /lib/async/future_impl.dart 766:44 handleValueCallback C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/async/future_impl.dart 795:13 _propagateToListeners C: /b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/async/future_impl.dart 557:7 [_complete] C:/b/s/w/ir/cache/builder /src/out/host_debug/dart-sdk/lib/async/stream_pipe.dart 61:11 _cancelAndValue C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/async /stream.dart 1530:7 C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/_internal/js_dev_runtime/private/ddc_runtime/operations.dart 334:14 _checkAndC all C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/_internal/js_dev_runtime/private/ ddc_runtime/operations.dart 339:39 dcall C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/html/dart2js/html_dart2js.dart 37309:58
所有 C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/_internal/js_dev_runtime/private/ ddc_runtime/operations.dart 339:39 dcall C:/b/s/ w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/html/dart2js/html_dart2js.dart 37309:58
at Object.createErrorWithStack (http://localhost:1681/dart_sdk.js:5093:12)
at Error._throw (http://localhost:1681/dart_sdk.js:20399:18)
at Error.throwWithStackTrace (http://localhost:1681/dart_sdk.js:20396:18)
at async._AsyncCallbackEntry.new.callback (http://localhost:1681/dart_sdk.js:40921:18)
at Object._microtaskLoop (http://localhost:1681/dart_sdk.js:40778:13)
at _startMicrotaskLoop (http://localhost:1681/dart_sdk.js:40784:13)
at http://localhost:1681/dart_sdk.js:36261:9
Yes it looks like it is a well known issue.是的,看起来这是一个众所周知的问题。 But all the answers I get on the web is or only going to work in debug or do not work at all.
但是我在网上得到的所有答案都是或只能在调试中工作或根本不起作用。 As far as I can figure it out you have to enable it on your server side.
据我所知,您必须在服务器端启用它。 Do anyone know how to enable it on server side so production web app can work?
有谁知道如何在服务器端启用它以便生产网络应用程序可以工作? Running apache with direct admin on it.
使用直接管理员运行 apache。 Not locally on pc but online.
不是在本地电脑上,而是在线。 Not looking for a temporary solution but looking for a solution that will work when in production.
不是在寻找临时解决方案,而是在寻找可以在生产中使用的解决方案。 Thank you
谢谢
I implemented the option to add any browser flag to the flutter command.我实现了将任何浏览器标志添加到 flutter 命令的选项。
flutter run -d chrome --web-browser-flag "--disable-web-security"
Or for drive
command:或者对于
drive
命令:
flutter drive --driver=test_driver/integration_test.dart --target=integration_test/app_test.dart -d web-server --web-browser-flag="--disable-web-security"
I have posted the answer for you question step by step here, you will need to make a few changes in order to allow CORS,我已在此处逐步发布您问题的答案,您需要进行一些更改才能允许 CORS,
The answer have been posted here: Flutter Web Http Error: Uncaught (in promise) Error: XMLHttpRequest error答案已发布在这里: Flutter Web Http 错误:未捕获(承诺)错误:Z6253F585154CE13C29EEE
1- Go to flutter\bin\cache and remove a file named: flutter_tools.stamp 1- Go 到 flutter\bin\cache 并删除一个名为:flutter_tools.stamp 的文件
2- Go to flutter\packages\flutter_tools\lib\src\web and open the file chrome.dart. 2- Go 到 flutter\packages\flutter_tools\lib\src\web 并打开文件 chrome.dart。
3- Find '--disable-extensions' 3-查找'--disable-extensions'
4- Add '--disable-web-security' 4-添加'--disable-web-security'
5- Add '--user-data-dir=/Users/mt/Desktop/chromedata' 5-添加'--user-data-dir=/Users/mt/Desktop/chromedata'
I feel silly for even admitting this, but I had some other local server running on the targeted port.我什至承认这一点都觉得很傻,但是我在目标端口上运行了一些其他本地服务器。 I've no clue why the server seemed to boot on the same port, or why the iOS app seemed to work, but now that I'm hitting the actual server it's working fine.
我不知道为什么服务器似乎在同一个端口上启动,或者为什么 iOS 应用程序似乎可以工作,但现在我正在访问实际的服务器,它工作正常。
I was also getting some 404's mixed in, but originally thought that was due to the CORs error.我也混入了一些 404,但最初认为这是由于 CORs 错误造成的。
Maybe someone else has this same issue and this helps them.也许其他人也有同样的问题,这对他们有帮助。
this How to solve flutter web api cors error only with dart code? this How to solve flutter web api cors error only with dart code? gives an Flutter Device Deamone exit code 1 error and does not solve it.
给出了 Flutter Device Deamone exit code 1 错误并且没有解决。 I'm just testing standalone on my PC from flutter to chrome and Edge and on both I get the XMLhttprequest error.
我只是在我的 PC 上从 flutter 到 chrome 和 Edge 进行独立测试,并且在两者上我都收到 XMLhttprequest 错误。
It Worked With Me By The Following Code: in conn.php file put like this:它通过以下代码与我一起工作:在conn.php文件中这样放置:
<?php
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST');
header("Access-Control-Allow-Headers: X-Requested-With");
$connect = new mysqli("localhost","db_user","db_password","db_name");
if($connect){
}else{
echo "Connection Failed";
exit();
}
This is a CORS (cross-origin resource sharing) issue and you just need to enable the CORS request from your server-side.这是一个 CORS(跨源资源共享)问题,您只需要从服务器端启用 CORS 请求即可。
In my case it is Asp.Net MVC Web API and adding below code to Application_BeginRequest
at Global.asax
worked for me:在我的例子中,它是Asp.Net MVC Web API并将以下代码添加到
Global.asax
的Application_BeginRequest
对我有用:
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "http://localhost:7777/");
if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
{
//These headers are handling the "pre-flight" OPTIONS call sent by the browser
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "POST, GET");
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "content-type");
HttpContext.Current.Response.End();
}
Use desired urls , Methods and Headers使用所需的url 、方法和标题
Also There is no need to change anything in Web.config此外,无需更改Web.config中的任何内容
If you are using FVM , I suggest to use flutter_cors
package如果你正在使用FVM ,我建议使用
flutter_cors
package
dart pub global activate flutter_cors
fluttercors --disable
If you face如果你面对
zsh: command not found: fluttercors
You need to add it to PATH.您需要将其添加到 PATH。 In my case, I'm using zsh, I add it to
.zshrc
by在我的例子中,我使用的是 zsh,我将它添加到
.zshrc
中
vim ~/.zshrc
Press I
to start editing and paste export PATH="$PATH":"$HOME/.pub-cache/bin"
to the top of the file按
I
开始编辑并将export PATH="$PATH":"$HOME/.pub-cache/bin"
粘贴到文件顶部
Then press ESC
and type :wq
to save the .zshrc
file.然后按
ESC
并键入:wq
以保存.zshrc
文件。 Now you're good to go现在你可以拨打 go
Now, just need to run your flutter web normally.现在,只需正常运行您的 flutter web 即可。 It will trigger Chrome without CORS.
它会在没有 CORS 的情况下触发 Chrome。
If anyone looking for an equivalent of the accepted answer (Osman's) when working with dart web (webdev), here's what worked for me on Dart 2.17.6 (a bit more complex but in case you needed a quick fix, it might be handful).如果有人在使用dart web (webdev) 时寻找等效的已接受答案 (Osman's),这就是我在 Dart 2.17.6 上工作的答案(有点复杂,但如果您需要快速修复,它可能很少).
The snapshot file (generated if not exist, as you see) is executed when you want to run app in browser.当您想在浏览器中运行应用程序时,将执行快照文件(如您所见,如果不存在则生成)。 It contains the code that dart runs when launching chrome (using
browser_launcher
dart package).它包含启动 chrome 时 dart 运行的代码(使用
browser_launcher
dart 包)。
Backup and remove the snapshot file (location in the screenshot above) so it can be regenerated in next run.备份并删除快照文件(上面屏幕截图中的位置),以便在下次运行时重新生成。
Locate browser_launcher
package in your pub cache (also you might find location of browser_launcher
by searching in the snapshot file) and edit lib\src\chrome.dart
, find '--disable-extensions'
and add '--disable-web-security'
.在您的发布缓存中找到
browser_launcher
package(您也可以通过在快照文件中搜索找到browser_launcher
的位置)并编辑lib\src\chrome.dart
,找到'--disable-extensions'
并添加'--disable-web-security'
。
Run your app and remove the backup created in step 2.运行您的应用并删除在第 2 步中创建的备份。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.