Flutter WEB请求到本地服务器

Flutter WEB request to local server

我遇到了一个问题,我正在使用 dio 来执行 http 请求,但是我得到了这个错误,即使我使用“http”依赖而不是“dio”,我已经使用了 ip、localhost 和 127.0 .0.1 地址但 none 有效。

你得到的错误

XMLHttp request error

很可能您没有在后端响应中启用 CORS: Cross-Origin Resource Sharing,这将使您可以通过指定的网站访问您的后端。

由于您使用的是 javascript,因此您必须在后端设置 CORS 并告诉后端您要从 javascript 应用程序发送请求。

要为每个网站启用 CORS,请将此 header 添加到后端的响应 header

Access-Control-Allow-Origin: *

来源意思

Web content's origin is defined by the scheme (protocol), hostname (domain), and port of the URL used to access it. Two objects have the same origin only when the scheme, hostname, and port all match (ref)

所以这将允许每个 网站访问您的后端,您可以通过将* 替换为您的网站地址来更改它。

其他 CORS Headers

还有许多其他选项可用于响应 header 和限制传入请求 请参阅 Cross-Origin Resource Sharing Mozilla 的文档

Access-Control-Allow-Methods: POST, GET, OPTIONS

The Access-Control-Request-Method header notifies the server as part of a preflight request that when the actual request is sent, it will be sent with a POST request method

Access-Control-Allow-Headers: X-PINGOTHER, Content-Type

The Access-Control-Request-Headers header notifies the server that when the actual request is sent, it will be sent with a X-PINGOTHER and Content-Type custom headers. The server now has an opportunity to determine whether it wishes to accept a request under these circumstances.

Access-Control-Max-Age: 86400

Finally, Access-Control-Max-Age gives the value in seconds for how long the response to the preflight request can be cached for without sending another preflight request. In this case, 86400 seconds is 24 hours. Note that each browser has a maximum internal value that takes precedence when the Access-Control-Max-Age is greater.