<ruby id="bdb3f"></ruby>

    <p id="bdb3f"><cite id="bdb3f"></cite></p>

      <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
        <p id="bdb3f"><cite id="bdb3f"></cite></p>

          <pre id="bdb3f"></pre>
          <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

          <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
          <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

          <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                <ruby id="bdb3f"></ruby>

                ??一站式輕松地調用各大LLM模型接口,支持GPT4、智譜、豆包、星火、月之暗面及文生圖、文生視頻 廣告
                Fetch和Axios請求默認是不帶cookie的 PS:感覺cookie使用的越來越少了,用戶認證有token方案,本地存儲有webStorage方案 [TOC] ## [Fetch API](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) The Fetch API provides an interface for?fetching resources (including across the network). It will seem familiar to anyone who has used [`XMLHttpRequest`](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest "Use XMLHttpRequest (XHR) objects to interact with servers. You can retrieve data from a URL without having to do a full page refresh. This enables a Web page to update just part of a page without disrupting what the user is doing."), but the new API provides a more powerful and flexible feature set. * provides a generic definition of [`Request`](https://developer.mozilla.org/en-US/docs/Web/API/Request "The Request interface of the Fetch API represents a resource request.") and [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response "The Response interface of the Fetch API represents the response to a request.") objects (and other things involved with network requests). * provides a definition for related concepts such as CORS and the HTTP origin header semantics, supplanting their separate definitions elsewhere. ### [Basic concepts](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Basic_concepts) At the heart of Fetch are the Interface abstractions of HTTP [`Request`](https://developer.mozilla.org/en-US/docs/Web/API/Request "The Request interface of the Fetch API represents a resource request.")s, [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response "The Response interface of the Fetch API represents the response to a request.")s, [`Headers`](https://developer.mozilla.org/en-US/docs/Web/API/Headers "The Headers interface of the Fetch API?allows you to perform various actions on HTTP request and response headers. These actions include retrieving, setting, adding to, and removing. A Headers object has an associated header list, which is initially empty and consists?of zero or more name and value pairs. ?You can add to this using methods like append() (see Examples.)?In all methods of this interface, header names are matched by case-insensitive byte sequence."), and [`Body`](https://developer.mozilla.org/en-US/docs/Web/API/Body "The Body mixin of the Fetch API represents the body of the response/request, allowing you to declare what its content type is and how it should be handled.") payloads, along with a [`global fetch`](https://developer.mozilla.org/en-US/docs/Web/API/GlobalFetch/fetch "The documentation about this has not yet been written; please consider contributing!") method for initiating asynchronous resource requests. Because the main components of HTTP are abstracted as JavaScript objects, it is easy for other APIs to make use of such functionality. [Service Workers](https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorker_API) is an example of an API that makes heavy use of Fetch. Fetch takes the asynchronous nature of such requests one step further. The API is completely [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise "The Promise object represents the eventual completion (or failure) of an asynchronous operation, and its resulting value.")\-based. ### Interfaces #### 1. `Body` [[MDN-官方文檔]](https://developer.mozilla.org/en-US/docs/Web/API/Body) Provides methods relating to the body of the response/request, allowing you to declare what its content type is and how it should be handled. #### 2. `Headers` [[MDN-官方文檔]](https://developer.mozilla.org/en-US/docs/Web/API/Headers) Represents response/request headers, allowing you to query them and take different actions depending on the results. The **`Headers`** interface of the `Fetch API`?allows you to perform various actions on `HTTP` request and response headers. These actions include retrieving, setting, adding to, and removing. A`Headers`object has an associated header list, which is initially empty and consists?of zero or more name and value pairs. ?You can add to this using methods like `append()`. In all methods of this interface, header names are matched by case-insensitive byte sequence. You can retrieve a `Headers` object via the `Request.headers` and `Response.headers` properties, and create a new `Headers` object using the `Headers.Headers()` constructor. An object implementing `Headers` can directly be used in a `for...of` structure, instead of `entries()`: `for (var p of myHeaders)` is equivalent to `for (var p of myHeaders.entries())`. >[warning] **Note**: you can find more out about the available headers by reading our [HTTP headers](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers) reference. **Constructor** `Headers()` Creates a new`Headers`object. **Methods** - `Headers.append()` Appends a new value onto an existing header inside a`Headers`object, or adds the header if it does not already exist. - `Headers.delete()` Deletes a header from a`Headers`object. - `Headers.entries()` Returns an `iterator` allowing to go through all key/value pairs contained in this object. - `Headers.forEach()` Executes a provided function once for each array element. - `Headers.get()` Returns a `ByteString` sequence?of all the values of a header within a`Headers`object with a given name. - `Headers.has()` Returns a boolean stating whether a`Headers`object contains a certain header. - `Headers.keys()` Returns an `iterator` allowing you to go through all keys of the key/value pairs contained in this object. - `Headers.set()` Sets a new value for an existing header inside a`Headers`object, or adds the header if it does not already exist. - `Headers.values()` Returns an `iterator` allowing you to go through all values of the key/value pairs contained in this object. Examples ~~~javascript var myHeaders = new Headers(); // using an append() method myHeaders.append('Content-Type', 'text/xml'); // or, using an object: var myHeaders = new Headers({ 'Content-Type': 'text/xml' }); // or, using an array of arrays: var myHeaders = new Headers([ ['Content-Type', 'text/xml'] ]); myHeaders.get('Content-Type') // should return 'text/xml' ~~~ #### 3. `Request` [[MDN-官方文檔]](https://developer.mozilla.org/en-US/docs/Web/API/Request) Represents a resource request. You can create a new `Request` object using the `Request()` constructor, but you are more likely to encounter a `Request` object being returned as the result of another API operation, such as a service worker [`FetchEvent.request`](https://developer.mozilla.org/en-US/docs/Web/API/FetchEvent/request "The request read-only property of the FetchEvent interface returns the Request that triggered the event handler."). **Constructor** `Request()` Creates a new`Request`object. **Properties** 常用 - `Request.url` | Read only Contains the URL of the request. - `Request.method` | Read only Contains the request's method (`GET`,`POST`, etc.) - `Request.mode` | Read only Contains the mode of the request (e.g.,`cors`,`no-cors`,`same-origin`,`navigate`.) - `Request.headers` | Read only Contains the associated `Headers` object of the request. - `Request.credentials` | Read only Contains the credentials of the request (e.g.,`omit`,`same-origin`,`include`). The default is`same-origin`. 不常用 - `Request.cache` | Read only Contains the cache mode of the request (e.g.,`default`,`reload`,`no-cache`). - `Request.context` | Read only Contains the context of the request (e.g.,`audio`,`image`,`iframe`, etc.) - `Request.destination` | Read only Returns a string from the `RequestDestination` enum describing the request's destination. This is a string indicating the type of content being requested. - `Request.integrity` | Read only Contains the subresource integrity value of the request (e.g.,`sha256-BpfBw7ivV8q2jLiT13fxDYAe2tJllusRSZ273h2nFSE=`). - `Request.redirect` | Read only Contains the mode for how redirects are handled. It may be one of`follow`,`error`, or`manual`. - `Request.referrer` | Read only Contains the referrer of the request (e.g.,`client`). - `Request.referrerPolicy` | Read only Contains the referrer policy of the request (e.g.,`no-referrer`). `Request`implements `Body`, so it also inherits the following properties: `body` | Read only A simple getter used to expose a[`ReadableStream`](https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream "The ReadableStream interface of the?Streams API?represents a readable stream of byte data. The Fetch API offers a concrete instance of a ReadableStream through the body property of a Response object.")of the body contents. `bodyUsed` | Read only Stores a `Boolean` that declares whether the body has been used in a response yet. **Methods** - `Request.clone()` Creates a copy of the current`Request`object. `Request` implements `Body`,so it also has the following methods available to it: - `Body.arrayBuffer()` Returns a promise that resolves with an[`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/API/ArrayBuffer "The documentation about this has not yet been written; please consider contributing!")representation of the request body. - `Body.blob()` Returns a promise that resolves with a `Blob` representation of the request body. A Blob object represents a file-like object of immutable, raw data; they can be read as text or binary data, or converted into a `ReadableStream` so its methods can be used for processing the data. Blobs can represent data that isn't necessarily in a JavaScript-native format. The File interface is based on Blob, inheriting blob functionality and expanding it to support files on the user's system. - `Body.formData()` Returns a promise that resolves with a `FormData` representation of the request body. The `formData()` method of the `Body` mixin takes a Response stream and reads it to completion. It returns a promise that resolves with a `FormData` object. The `FormData` interface provides a way to easily construct a set of key/value pairs representing form fields and their values, which can then be easily sent using the `XMLHttpRequest.send()` method. It uses the same format a form would use if the encoding type were set to "multipart/form-data". - `Body.json()` Returns a promise that resolves with a`JSON`representation of the request body. The `json()` method of the Body mixin takes a Response stream and reads it to completion. It returns a promise that resolves with the result of parsing the body text as JSON. - `Body.text()` Returns a promise that resolves with an `USVString` (text) representation of the request body.. The `text()` method of the `Body` mixin takes a Response stream and reads it to completion. It returns a promise that resolves with a USVString object (text).?The response is?always?decoded using UTF-8. `USVString` corresponds to the set of all possible sequences of unicode scalar values. `USVString` maps to a `String` when returned in JavaScript; it's generally only used for APIs that perform text processing and need a string of unicode scalar values to operate on. `USVString` is equivalent to `DOMString` except for not allowing unpaired surrogate codepoints. Unpaired surrogate codepoints present in `USVString` are converted by the browser to Unicode 'replacement character' U+FFFD, (?). Examples: ~~~javascript const request = new Request('https://example.com', {method: 'POST', body: '{"foo": "bar"}'}); const URL = request.url; const method = request.method; const credentials = request.credentials; const bodyUsed = request.bodyUsed; fetch(request) .then(response => { if (response.status === 200) { return response.json(); } else { throw new Error('Something went wrong on api server!'); } }) .then(response => { console.debug(response); // ... }).catch(error => { console.error(error); }); ~~~ >[warning] **Note:** The body type can only be a `Blob`, `BufferSource`, `FormData`, `URLSearchParams`, `USVString` or `ReadableStream` type, so for adding a JSON object to the payload you need to stringify that object. #### 4. `Response` [[MDN-官方文檔]](https://developer.mozilla.org/en-US/docs/Web/API/Response) Represents the response to a request. [[MDN Response]](https://developer.mozilla.org/en-US/docs/Web/API/Response) The **`Response`** interface of the [Fetch API](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) represents the response to a request. The `fetch()` call returns a promise, which resolves with the `Response` object associated with the resource fetch operation. - **Constructor** `Response()`: Creates a new `Response` object. - **Properties** | 序號 | 表達 | 說明 | | --- | --- | --- | | 1. | `Response.headers` | `Read only`, <br>Contains the `Headers` object associated with the response.| | 2. | `Response.ok`| `Read only`, <br>Contains a boolean stating whether the response was successful (status in the range 200-299) or not. | | 3. | `Response.redirected` | `Read only`, <br>Indicates whether or not the response is the result of a redirect; that is, its URL list has more than one entry. | | 4. | `Response.status` | `Read only`, <br>Contains the status code of the response (e.g., `200` for a success). | | 5. | `Response.statusText` | `Read only`, <br>Contains the status message corresponding to the status code (e.g., `OK` for `200`). | | 6. | `Response.type` | `Read only`, <br>Contains the type of the response (e.g., `basic`, `cors`). | | 7. | `Response.url` | `Read only`, <br>Contains the URL of the response. | | 8. | `Response.useFinalURL` | Contains a boolean stating whether this is the final URL of the response. | `Response` implements [`Body`](https://developer.mozilla.org/en-US/docs/Web/API/Body "The Body mixin of the Fetch API represents the body of the response/request, allowing you to declare what its content type is and how it should be handled."), so it also has the following properties available to it: [`Body.body`](https://developer.mozilla.org/en-US/docs/Web/API/Body/body "The body read-only property of the Body mixin is a simple getter used to expose a ReadableStream of the body contents.") Read only, A simple getter used to expose a [`ReadableStream`](https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream "The ReadableStream interface of the?Streams API?represents a readable stream of byte data. The Fetch API offers a concrete instance of a ReadableStream through the body property of a Response object.") of the body contents. [`Body.bodyUsed`](https://developer.mozilla.org/en-US/docs/Web/API/Body/bodyUsed "The bodyUsed read-only property of the Body mixin contains a Boolean that indicates whether the body has been read yet.") Read only, Stores a [`Boolean`](https://developer.mozilla.org/en-US/docs/Web/API/Boolean "REDIRECT Boolean [en-US]") that declares whether the body has been used in a response yet. **Methods** | 序號 | 表達 | 說明 | | --- | --- | --- | | 1. | `Response.clone()` | Creates a clone of a `Response` object. | | 2. | `Response.error()` | Returns a new `Response` object associated with a network error. | | 3. | `Response.redirect()` | Creates a new response with a different URL. | | 4. | `Body.arrayBuffer()`* | Takes a `Response` stream and reads it to completion. It returns a promise that resolves with an [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/API/ArrayBuffer "The documentation about this has not yet been written; please consider contributing!"). | | 5. | `Body.blob()`* | Takes a `Response` stream and reads it to completion. It returns a promise that resolves with a [`Blob`](https://developer.mozilla.org/en-US/docs/Web/API/Blob "A Blob object represents a file-like object of immutable, raw data. Blobs represent data that isn't necessarily in a JavaScript-native format. The File interface is based on Blob, inheriting blob functionality and expanding it to support files on the user's system."). | | 6. | `Body.formData()`* | Takes a `Response` stream and reads it to completion. It returns a promise that resolves with a [`FormData`](https://developer.mozilla.org/en-US/docs/Web/API/FormData "The FormData interface provides a way to easily construct a set of key/value pairs representing form fields and their values, which can then be easily sent using the XMLHttpRequest.send() method. It uses the same format a form would use if the encoding type were set to "multipart/form-data".") object. | | 7. | `Body.json()`* | Takes a `Response` stream and reads it to completion. It returns a promise that resolves with the result of parsing the body text as?[`JSON`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON "The JSON object contains methods for parsing JavaScript Object Notation (JSON) and converting values to JSON. It can't be called or constructed, and aside from its two method properties, it has no interesting functionality of its own."). | | 8. | `Body.text()`* | Takes a `Response` stream and reads it to completion. It returns a promise that resolves with a [`USVString`](https://developer.mozilla.org/en-US/docs/Web/API/USVString "USVString corresponds to the set of all possible sequences of unicode scalar values. USVString maps to a String when returned in JavaScript; it's generally only used for APIs that perform text processing and need a string of unicode scalar values to operate on. USVString is equivalent to DOMString except for not allowing unpaired surrogate codepoints. Unpaired surrogate codepoints present in USVString are converted by the browser to Unicode 'replacement character' U+FFFD, (?).") (text). | *`Response` implements `Body`, so it also has the following methods available to it: ### method [`WindowOrWorkerGlobalScope.fetch()`](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch) The?`fetch()`?method takes one mandatory argument, the path to the resource you want to fetch. It?returns a [`Promise`](https://developer.mozilla.org/en-US/docs/Web/API/Promise "REDIRECT Promise") that resolves to the [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response "The Response interface of the Fetch API represents the response to a request.") to that request, whether it is successful or not. You can also optionally pass in an `init` options object as the second argument (see [`Request`](https://developer.mozilla.org/en-US/docs/Web/API/Request "The Request interface of the Fetch API represents a resource request.")) >[info] `fetch()`方法返回的是一個`Promise`對象,這個`Promise`對象會被resolve成一個`response`對象,該`response`對象就是對使用`fetch()`方法所發起的`request`的響應結果。 ### Aborting a fetch Browsers have started to add experimental support for the [`AbortController`](https://developer.mozilla.org/en-US/docs/Web/API/AbortController "The AbortController interface represents a controller object that allows you to abort one or more DOM requests as and when desired.") and [`AbortSignal`](https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal "The AbortSignal interface represents a signal object that allows you to communicate with a DOM request (such as a Fetch) and abort it if required via an AbortController object.") interfaces (aka The Abort API), which allow operations like Fetch and XHR to be aborted if they have not already completed. See the interface pages for more details. ## Using Fetch [[MDN Fetch]](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch) [[MDN Using Fetch]](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch) The`fetch`specification differs from`jQuery.ajax()`in two main ways: * The Promise returned from`fetch()`**won’t reject on HTTP error status** even if the response is an HTTP 404 or 500. Instead, it will resolve normally (with`ok`status set to false), and it will only reject on network failure or if anything prevented the request from completing. * By default,`fetch`**won't send or receive any cookies** from the server, resulting in unauthenticated requests if the site relies on maintaining a user session (to send cookies, the*credentials*[init option](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch#Parameters)must be set). Since [Aug 25, 2017](https://github.com/whatwg/fetch/pull/585). The spec changed the default credentials policy to`same-origin`. Firefox changed since 61.0b13. A basic fetch request is really simple to set up. Have a look at the following code: ~~~js fetch('http://example.com/movies.json') .then(function(response) { return response.json(); }) .then(function(myJson) { console.log(JSON.stringify(myJson)); }); ~~~ ### Syntax ~~~js fetchResponsePromise = fetch(resource, init); ~~~ **`resource`** This defines the resource that you wish to fetch. This can either be: * A[`USVString`](https://developer.mozilla.org/en-US/docs/Web/API/USVString "USVString corresponds to the set of all possible sequences of unicode scalar values. USVString maps to a String when returned in JavaScript; it's generally only used for APIs that perform text processing and need a string of unicode scalar values to operate on. USVString is equivalent to DOMString except for not allowing unpaired surrogate codepoints. Unpaired surrogate codepoints present in USVString are converted by the browser to Unicode 'replacement character' U+FFFD, (?).")containing the direct URL of the resource you want to fetch. Some browsers accept`blob:`and`data:`as schemes. * A[`Request`](https://developer.mozilla.org/en-US/docs/Web/API/Request "The Request interface of the Fetch API represents a resource request.")object. **`init`**(Optional) An options object containing any custom settings that you want to apply to the request. The possible options are: * `method`: The request method, e.g.,`GET`,`POST`. Note that the[`Origin`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Origin "The Origin request header indicates where a fetch originates from. It doesn't include any path information, but only the server name. It is sent with CORS requests, as well as with POST requests. It is similar to the Referer header, but, unlike this header, it doesn't disclose the whole path.")header is not set on Fetch requests with a method of`[HEAD](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/HEAD)`or`[GET](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/GET)`(this behavior was corrected in Firefox 65 — see[bug?1508661](https://bugzilla.mozilla.org/show_bug.cgi?id=1508661 "FIXED: origin header should not be set for GET and HEAD requests")). * `headers`: Any headers you want to add to your request, contained within a[`Headers`](https://developer.mozilla.org/en-US/docs/Web/API/Headers "The Headers interface of the Fetch API?allows you to perform various actions on HTTP request and response headers. These actions include retrieving, setting, adding to, and removing. A Headers object has an associated header list, which is initially empty and consists?of zero or more name and value pairs. ?You can add to this using methods like append() (see Examples.)?In all methods of this interface, header names are matched by case-insensitive byte sequence.")object or an object literal with[`ByteString`](https://developer.mozilla.org/en-US/docs/Web/API/ByteString "ByteString is a UTF-8 String that corresponds to the set of all possible sequences of bytes. ByteString maps to a String when returned in JavaScript; generally, it's only used when interfacing with protocols that use bytes and strings interchangably, such as HTTP.")values. Note that[some names are forbidden](https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_header_name). * `body`: Any body that you want to add to your request: this can be a[`Blob`](https://developer.mozilla.org/en-US/docs/Web/API/Blob "A Blob object represents a file-like object of immutable, raw data. Blobs represent data that isn't necessarily in a JavaScript-native format. The File interface is based on Blob, inheriting blob functionality and expanding it to support files on the user's system."),[`BufferSource`](https://developer.mozilla.org/en-US/docs/Web/API/BufferSource "BufferSource is a?typedef used to represent?objects that are either themselves an ArrayBuffer, or which are a TypedArray providing an ArrayBufferView."),[`FormData`](https://developer.mozilla.org/en-US/docs/Web/API/FormData "The FormData interface provides a way to easily construct a set of key/value pairs representing form fields and their values, which can then be easily sent using the XMLHttpRequest.send() method. It uses the same format a form would use if the encoding type were set to "multipart/form-data"."),[`URLSearchParams`](https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams "The URLSearchParams interface defines utility methods to work with the query string of a URL."), or[`USVString`](https://developer.mozilla.org/en-US/docs/Web/API/USVString "USVString corresponds to the set of all possible sequences of unicode scalar values. USVString maps to a String when returned in JavaScript; it's generally only used for APIs that perform text processing and need a string of unicode scalar values to operate on. USVString is equivalent to DOMString except for not allowing unpaired surrogate codepoints. Unpaired surrogate codepoints present in USVString are converted by the browser to Unicode 'replacement character' U+FFFD, (?).")object. Note that a request using the`GET`or`HEAD`method cannot have a body. * `mode`: The mode you want to use for the request, e.g.,`cors`,`no-cors`, or`same-origin`. * `credentials`: The request credentials you want to use for the request:`omit`,`same-origin`, or`include`.?To automatically send cookies for the current domain, this?option must be provided. Starting with Chrome 50, this property also takes a[`FederatedCredential`](https://developer.mozilla.org/en-US/docs/Web/API/FederatedCredential "The FederatedCredential interface of the the Credential Management API provides information about credentials from a federated identity provider. A federated identity provider is an entity that a website trusts to correctly authenticate a user, and that provides an API for that purpose. OpenID Connect is an example of a federated identity provider framework.")instance or a[`PasswordCredential`](https://developer.mozilla.org/en-US/docs/Web/API/PasswordCredential "The interface of the Credential Management API provides information about a username/password pair.?In supporting browsers an instance of this class may be passed in the credential member of the init object for global fetch.")instance. * `cache`: The[cache mode](https://developer.mozilla.org/en-US/docs/Web/API/Request/cache)you want to use for the request. * `redirect`: The redirect mode to use:`follow`(automatically follow redirects),`error`(abort with an error if a redirect occurs), or`manual`(handle redirects manually). In Chrome the default is?`follow`?(before Chrome 47 it defaulted to?`manual`). * `referrer`: A[`USVString`](https://developer.mozilla.org/en-US/docs/Web/API/USVString "USVString corresponds to the set of all possible sequences of unicode scalar values. USVString maps to a String when returned in JavaScript; it's generally only used for APIs that perform text processing and need a string of unicode scalar values to operate on. USVString is equivalent to DOMString except for not allowing unpaired surrogate codepoints. Unpaired surrogate codepoints present in USVString are converted by the browser to Unicode 'replacement character' U+FFFD, (?).")specifying?`no-referrer`,?`client`, or a URL. The default is?`client`. * `referrerPolicy`: Specifies the value of the referer HTTP header. May be one of`no-referrer`,`no-referrer-when-downgrade`,`origin`,`origin-when-cross-origin`,`unsafe-url`. * `integrity`: Contains the[subresource integrity](https://developer.mozilla.org/en-US/docs/Web/Security/Subresource_Integrity)value?of the request (e.g.,`sha256-BpfBw7ivV8q2jLiT13fxDYAe2tJllusRSZ273h2nFSE=`). * `keepalive`: The`keepalive`option can be used to allow the request to outlive the page. Fetch with the`keepalive`flag is a replacement for the[`Navigator.sendBeacon()`](https://developer.mozilla.org/en-US/docs/Web/API/Navigator/sendBeacon "The navigator.sendBeacon() method can be used to asynchronously transfer a small amount of data over HTTP to a web server.")API.? * `signal`: An[`AbortSignal`](https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal "The AbortSignal interface represents a signal object that allows you to communicate with a DOM request (such as a Fetch) and abort it if required via an AbortController object.")object instance; allows you to communicate with a fetch request and abort it if desired via an[`AbortController`](https://developer.mozilla.org/en-US/docs/Web/API/AbortController "The AbortController interface represents a controller object that allows you to abort one or more DOM requests as and when desired."). ### Return value A `Promise` that resolves to a `Response` objec ### Supplying request options The`fetch()`method can optionally accept a second parameter, an`init`object that allows you to control a number of different settings: See[`fetch()`](https://developer.mozilla.org/en-US/docs/Web/API/GlobalFetch/fetch "The documentation about this has not yet been written; please consider contributing!")for the full options available, and more details. ~~~js // Example POST method implementation: postData('http://example.com/answer', {answer: 42}) .then(data => console.log(JSON.stringify(data))) // JSON-string from `response.json()` call .catch(error => console.error(error)); function postData(url = '', data = {}) { // Default options are marked with * return fetch(url, { method: 'POST', // *GET, POST, PUT, DELETE, etc. mode: 'cors', // no-cors, cors, *same-origin cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached credentials: 'same-origin', // include, *same-origin, omit headers: { 'Content-Type': 'application/json', // 'Content-Type': 'application/x-www-form-urlencoded', }, redirect: 'follow', // manual, *follow, error referrer: 'no-referrer', // no-referrer, *client body: JSON.stringify(data), // body data type must match "Content-Type" header }) .then(response => response.json()); // parses JSON response into native JavaScript objects } ~~~ ### CORS(Cross-Origin Resource Sharing) [[MDN-CORS]](https://developer.mozilla.org/en-US/docs/Glossary/CORS) Cross-Origin Resource Sharing (CORS), is a machanism/protocal/system, consisting of transmitting HTTP headers, that determines whether browsers block frontend JavaScript code from accessing responses for cross-origin requests. A web application executes a **cross-origin HTTP request** when it requests a resource that has a different origin (domain, protocol, or port) from its own. ![CORS_principle](https://img.kancloud.cn/c2/74/c274d3ad68f9b67e9509024793d3c729_925x643.png) The CORS mechanism supports secure cross-origin requests and data transfers between browsers and servers. Modern browsers use CORS in a APIs such as `XMLHttpRequest` or `Fetch` to mitigate the risks of cross-origin HTTP requests. 同源策略:是指協議,域名,端口都要相同,其中有一個不同都會產生跨域; 跨域:指的是瀏覽器不能執行其他網站的腳本。它是由瀏覽器的同源策略造成的,是瀏覽器對javascript施加的安全限制。 例如:a頁面想獲取b頁面資源,如果a、b頁面的協議、域名、端口、子域名不同,所進行的訪問行動都是跨域的,而瀏覽器為了安全問題一般都限制了跨域訪問,也就是不允許跨域請求資源。注意:跨域限制訪問,其實是**瀏覽器的限制**。理解這一點很重要!!! 假設有兩個網站,A網站部署在:http://localhost:81 即本地ip端口81上;B網站部署在:http://localhost:82 即本地ip端口82上。現在A網站的頁面想去訪問B網站的信息,就會出現跨域問題。 用nginx作為代理服務器和用戶交互,這樣用戶就只需要在80端口上進行交互就可以了,這樣就避免了跨域問題,因為我們都是在80端口上進行交互的; 下面我們看一下利用nginx作為反向代理的具體配置: > server { > > ? ? ? ? listen? ? ? 80; #監聽80端口,可以改成其他端口 > > ? ? ? ? server\_name? localhost; # 當前服務的域名 > > ? ? ? ? #charset koi8-r; > > ? ? ? ? #access\_log? logs/host.access.log? main; > > ? ? ? ? location / { > > ? ? ? ? ? ? proxy\_pass http://localhost:81; > > ? ? ? ? ? ? proxy\_redirect default; > > ? ? ? ? } > > location /apis { #添加訪問目錄為/apis的代理配置 > > rewrite? ^/apis/(.\*)$ /$1 break; > > proxy\_pass? http://localhost:82; > > ? ? ? } > > #以下配置省略 1.當用戶發送localhost:80/時會被nginx轉發到http://localhost:81服務; 2.當界面請求接口數據時,只要以/apis 為開頭,就會被nginx轉發到后端接口服務器上; 總結:nginx實現跨域的原理,實際就是把web項目和后端接口項目放到一個域中,這樣就不存在跨域問題,然后根據請求地址去請求不同服務器(真正干活的服務器); 作者:少年仍年少 鏈接:https://www.jianshu.com/p/8fa2acd103ea 來源:簡書 著作權歸作者所有。商業轉載請聯系作者獲得授權,非商業轉載請注明出處。 #### Overview The Cross-Origin Resource Sharing standard works by adding new [HTTP headers](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers) that let servers describe which origins are permitted to read that information from a web browser. Additionally, for HTTP request methods that can cause side-effects on server data (in particular, HTTP methods other than [`GET`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/GET "The HTTP GET method requests a representation of the specified resource. Requests using GET should only retrieve data."), or [`POST`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/POST "The HTTP POST method sends data to the server. The type of the body of the request is indicated by the Content-Type header.") with certain [MIME types](https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types)), the specification mandates that browsers "preflight" the request, soliciting supported methods from the server with the HTTP [`OPTIONS`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/OPTIONS "The HTTP OPTIONS method is used to describe the communication options for the target resource. The client can specify a URL for the OPTIONS method, or an asterisk (*) to refer to the entire server.") request method, and then, upon "approval" from the server, sending the actual request. Servers can also inform clients whether "credentials" (such as [Cookies](https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies) and [HTTP Authentication](https://developer.mozilla.org/en-US/docs/Web/HTTP/Authentication)) should be sent with requests. CORS failures result in errors, but for security reasons, specifics about the error *are not available to JavaScript*. All the code knows is that an error occurred. The only way to determine what specifically went wrong is to look at the browser's console for details. #### [Server-Side Access Control ](https://developer.mozilla.org/en-US/docs/Web/HTTP/Server-Side_Access_Control) TP5.1 跨域請求 如果某個路由或者分組需要支持跨域請求,可以使用 ~~~php Route::get('new/:id', 'News/read') ->ext('html') ->allowCrossDomain(); ~~~ > 跨域請求一般會發送一條`OPTIONS`的請求,一旦設置了跨域請求的話,不需要自己定義`OPTIONS`請求的路由,系統會自動加上。 跨域請求系統會默認帶上一些Header,包括: ~~~php Access-Control-Allow-Origin:* Access-Control-Allow-Methods:GET, POST, PATCH, PUT, DELETE Access-Control-Allow-Headers:Authorization, Content-Type, If-Match, If-Modified-Since, If-None-Match, If-Unmodified-Since, X-Requested-With ~~~ 你可以添加或者更改Header信息,使用 ~~~php Route::get('new/:id', 'News/read') ->ext('html') ->header('Access-Control-Allow-Origin','thinkphp.cn') ->header('Access-Control-Allow-Credentials', 'true') ->allowCrossDomain(); ~~~ ## Method(GET, POST, PUT, DELETE) ### POST **post使用`multipart/form-data`和`application/x-www-form-urlencoded`的本質區別** [[參考網頁]](https://blog.csdn.net/u013827143/article/details/86222486) * `application/x-www-form-urlencoded` 1、它是post的默認格式,使用js中`URLencode`轉碼方法。包括將name、value中的空格替換為加號;將非ascii字符做百分號編碼;將input的name、value用‘=’連接,不同的input之間用‘&’連接。 2、百分號編碼什么意思呢。比如漢字‘丁’吧,他的utf8編碼在十六進制下是0xE4B881,占3個字節,把它轉成字符串‘E4B881’,變成了六個字節,每兩個字節前加上百分號前綴,得到字符串“%E4%B8%81”,變成九個ascii字符,占九個字節(十六進制下是0x244534254238253831)。把這九個字節拼接到數據包里,這樣就可以傳輸“非ascii字符的? utf8編碼的 十六進制表示的 字符串的 百分號形式”,^_^。 3、同樣使用URLencode轉碼,這種post格式跟get的區別在于,get把轉換、拼接完的字符串用`?`直接與表單的action連接作為URL使用,所以請求體里沒有數據;而post把轉換、拼接后的字符串放在了請求體里,不會在瀏覽器的地址欄顯示,因而更安全一些。 * `multipart/form-data` 1、對于一段utf8編碼的字節,用`application/x-www-form-urlencoded`傳輸其中的ascii字符沒有問題,但對于非ascii字符傳輸效率就很低了(漢字‘丁’從三字節變成了九字節),因此在傳很長的字節(如文件)時應用`multipart/form-data`格式。`smtp`等協議也使用或借鑒了此格式。 2、此格式表面上發送了什么呢。用此格式發送一段一句話和一個文件,同時請求頭里規定了`Content-Type: multipart/form-data; boundary=----WebKitFormBoundarymNhhHqUh0p0gfFa`,請求體里不同的input之間用一段叫boundary的字符串分割,每個input都有了自己一個小header,其后空行接著是數據。 `multipart/form-data`將表單中的每個input轉為了一個由boundary分割的小格式,沒有轉碼,直接將utf8字節拼接到請求體中,在本地有多少字節實際就發送多少字節,極大提高了效率,適合傳輸長字節。 在`Form`元素的語法中,`EncType`表明提交數據的格式。用`Enctype`屬性指定將數據回發到服務器時瀏覽器使用的編碼類型。 - `application/x-www-form-urlencoded`: 窗體數據被編碼為名稱/值對。這是標準的編碼格式。 - `multipart/form-data`: 窗體數據被編碼為一條消息,頁上的每個控件對應消息中的一個部分。 - ` text/plain`: 窗體數據以純文本形式進行編碼,其中不含任何控件或格式字符。 常用的為前兩種:`application/x-www-form-urlencoded`和`multipart/form-data`,默認為`application/x-www-form-urlencoded`。 當`action`為`get`時候,瀏覽器用`x-www-form-urlencoded`的編碼方式把form數據轉換成一個字串(name1=value1&name2=value2…),然后把這個字串append到url后面,用`?`分割,加載這個新的url。 當`action`為`pos`t時候,瀏覽器把form數據封裝到http body中,然后發送到server。 如果沒有`type=file`的控件,用默認的`application/x-www-form-urlencoded`就可以了。 但是如果有`type=file`的話,就要用到`multipart/form-data`了。瀏覽器會把整個表單以控件為單位分割,并為每個部分加上`Content-Disposition`(form-data或者file),`Content-Type`(默認為text/plain),name(控件name)等信息,并加上分割符(`boundary`). ## 待求證 ### 1. Credentials的配置使用 `Access-Control-Allow-Credentials` 頭與{domxref(“XMLHttpRequest.withCredentials”)}} 或Fetch API中的Request() 構造器中的`credentials` 選項結合使用。Credentials必須在前后端都被配置(即the `Access-Control-Allow-Credentials` header 和 XHR 或Fetch request中都要配置)才能使帶credentials的CORS請求成功。
                  <ruby id="bdb3f"></ruby>

                  <p id="bdb3f"><cite id="bdb3f"></cite></p>

                    <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
                      <p id="bdb3f"><cite id="bdb3f"></cite></p>

                        <pre id="bdb3f"></pre>
                        <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

                        <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
                        <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

                        <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                              <ruby id="bdb3f"></ruby>

                              哎呀哎呀视频在线观看