Home > Web Front-end > JS Tutorial > [Compilation and Summary] Several practical response headers that the front-end must know

[Compilation and Summary] Several practical response headers that the front-end must know

青灯夜游
Release: 2022-09-14 19:43:07
forward
2878 people have browsed it

[Compilation and Summary] Several practical response headers that the front-end must know

Read this article, you will:

  • Learn a few super and super practical Response headers, solve the problems you encounter at work.

  • Not only solves the problem, but also gives you the upper hand when you are at odds with the backend and operation and maintenance.

Is it important to learn response headers?

It’s really important.

If you don’t believe me, take a look at the scene below. Does it look familiar?

1. Are you worried about previewing and downloading?

1.1 Scenario

I heard from my colleagues more than once , group friends discussed this issue:

"The backend provides a

txt (or pdf/'json', etc.) file downloadurl, but when I open it with the a tag, it turns into a preview... What should I do? Save!!!"

At this time, someone will Go up and recommend

FileSaver.js or "Save handwritten reading stream as".

Then someone else echoed...

Me:? ? ?

[Compilation and Summary] Several practical response headers that the front-end must know

Is this a problem that requires writing code to solve?

If you have learned about

Content-Disposition Response Header, then you must know that the problem can be solved by just adding a line to the response header.

1.2 Introduction

Content-Disposition: This response header can determine whether the content is Preview Or download.

It supports three formats of values:

  • Content-Disposition: inlineAt this time, the message body will be part of the page or Displayed in the form of the entire page. (Preview)

  • Content-Disposition: attachmentThe message body should be downloaded, and the default file name is related to the
    url format.

  • Content-Disposition: attachment; filename="filename.jpg"The message body should be downloaded, and the default file name can be specified.

Note: If you need to preview, you need to match the appropriate

Content-Type for consumption;

##1.3 Example

To this end, I specially wrote a

express

small example. I probably wrote three routes under the

express

application, as follows: <div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false">const user = {   name: &quot;摸鱼的春哥&quot;,   blogUrl: &quot;https://juejin.cn/user/1714893870865303&quot; } const contentDispositionInline = async (req, res, next) =&gt; {   res.setHeader('Content-Disposition', 'inline')   res.send(user) } const contentDispositionFilename = async (req, res, next) =&gt; {   res.setHeader('Content-Disposition', 'attachment; filename=&quot;chunge.json&quot;')   res.send(user) } const contentDispositionNoFilename = async (req, res, next) =&gt; {   res.setHeader('Content-Disposition', 'attachment')   res.send(user) }</pre><div class="contentsignin">Copy after login</div></div> Then I visited the three routes respectively, and the effect was different:

[Compilation and Summary] Several practical response headers that the front-end must know

2. The project has been upgraded. Does the customer need to clear the cache?

2.1 Scenario

Implementation: "Customer feedback

Bug

is still not fixed." You: "Brother, it’s really fixed How about you ask the customer to clear the cache?"Implementation: "Ah? The customer said he won't clear it..."
...

Never expect your customer to do it. Perform operations that

"only those in R&D understand"

. Don't attribute your problem to browser cache either.

Browser cache

was invented to optimize user experience, not to hinder users. Therefore, understanding how to use the

Cache-Control

response header is a must-know skill for the front-end.

2.2 Introduction

Cache-Control: Used to specify the caching mechanism. Caching, as a required knowledge for front-end eight-part essays, I believe everyone is familiar with it. Common

Cache-Control attributes are as follows:

Response Header Attribute Value Meaning
cache-control no-store No caching, this will cause neither the client nor the server to cache, and there will be no so-called strong caching or negotiated caching.
cache-control public Indicates that the response can be cached by any object (including: the client sending the request, the proxy server, etc.) , even for content that is not normally cacheable. (For example: 1. This response does not have a max-age directive or Expires header; 2. The request method corresponding to this response is POST.)
cache-control private indicates that the response can only be cached by a single user, not as a shared cache (i.e. the proxy server cannot cache it). A private cache can cache response content, for example, corresponding to the user's local browser.
cache-control max-age= Set the maximum period for cache storage. After this time, the cache is considered expired ( unit seconds). In contrast to Expires, the time is relative to the time of the request.
  • No caching
    No caching is the easiest to understand. Every request will be re-obtained from the server without any caching.
    This strategy only needs to be given the Cache-Control: no-store response header.
  • Strong Cache
    Some resource files will almost never change (such as files that have been hash-named), which can be obtained directly from the local cache. This is the so-called Strong cache ;
    You can specify the mechanism as strong cache through cache-control: public/private or cache-control: max-age= .
  • Negotiation Caching
    This is a more complex caching mechanism that can no longer be implemented simply and crudely through the response header . Instead, it requires front-end and back-end collaboration.
    Simply put, every time a resource is requested, the front end will write the previous response hash and ask the server whether the resource has changed, so as to achieve accurate caching effect. .
    This article will not go into details. If you are interested, you can refer to this article: juejin.cn/post/703078…

2.3 How to apply it in actual production?

  • Any resource whose name has a hash value can be strongly cached.
    (After all, once the content changes, the hash of the name will also change)
  • It is recommended to carry version information for all third-party libraries introduced through cdn , which can also enable strong caching.
    (For example, /xx/xx/jquery.min.js switches to jquery@3.6.0/dist/jquery.min.js)
  • Any html, ico It is recommended that files with fixed names such as not be cached or negotiate cache.

3. My Cookie can’t be so cute!

3.1 Scenario

"Brother Chun, why is it that my login is successful but the request is still 401?"

"Brother Chun, why can't I get the value I deposited into cookie?"

" Brother Chun, Brother Chun, is this cookie broken? It’s obviously valuable in the browser, why can’t I access it?"

Me: "Brother, do you have it? Have you ever heard of a response header called set-cookie?”

[Compilation and Summary] Several practical response headers that the front-end must know

That’s it! That's it! that's it! All kinds of anomalies about cookie, all rely on it!

3.2 Introduction

Cookie used to be Web It is a threshold that cannot be bypassed in development, and now its existence is getting weaker and weaker, but the large number of existing projects will not disappear due to technological trends. They are still valuable and still need to be maintained.

And the set-cookie response header is the core first protagonist of the Cookie system.

Set-Cookie: is a response header, assigned by the server, allowing the browser to generate Cookie and limit Cookie various features.

These features include:

  • Expiration time limit;Expires=<date></date>
  • Lifetime;Max-Age=<number></number>
    Invalid cookie The number of seconds to elapse before. 0 or -1 is directly invalid; this attribute has a higher priority than Expires.
  • Domain name;Domain=<domain-value></domain-value>
    Specify the domain in which cookie can only be generated; (Wildcarding is allowed, this attribute is mainly used for For security)
  • Path; Path=<path-value></path-value>
    is a more detailed control strategy than Domain, and even specifies Cookie can be sent only under the xx path.
  • Only generated in Https; Secure
    If there is Secure attribute in the set-cookie header, then The browser will only generate and send Cookie in the Https environment.
  • Disablejs Operation API; HttpOnly
    If set-cookie has HttpOnly in the header attribute, then the generation, reading, writing, and sending of the Cookie attribute can only be controlled by the browser through the "response header", and the front end is no longer allowed to operate through js Cookie.
  • Whether cross-domain portability is allowed; SameSite=<samesite-value></samesite-value>
    Supported attributes include Strict, Lax, None, respectively means:
    • Strict: cannot be carried across domains at all;
    • Lax: only allows navigation from external sites. When originating, carry Cookie
    • ##None: cross-domain is also allowed, no restriction.

3.3 Analysis of Development Frequently Asked Questions

  • Why did you log in successfully but the request was still

    401?

    Many early projects used

    Cookie as a means of user identification. For example, the Spring MVC project is by giving Cookie a ## The value of #JSeesionId is used as identification to determine whether you are in the current session. As for the phenomenon of "Logged in, but still

    401

    ", if there is no problem on the server side, it is probably that the browser does not actually store Cookie. In other words, every time you initiate a request, the server thinks that you are a

    new session

    , and you are not the same person as the last login. If you are in a

    http

    environment, you may need to temporarily remove the Secure attribute.

  • Can’t deposit or withdraw?
  • First confirm whether

    is subject to domain restrictions
    , Whether there are path restrictions , Are there HttpOnly? Check one by one Come down, the problem is not difficult to solve.

  • (Learning video sharing:
web front-end

)

The above is the detailed content of [Compilation and Summary] Several practical response headers that the front-end must know. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:juejin.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template