search
HomeWeb Front-endJS 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

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: <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> 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.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!

Statement
This article is reproduced at:掘金社区. If there is any infringement, please contact admin@php.cn delete
es6数组怎么去掉重复并且重新排序es6数组怎么去掉重复并且重新排序May 05, 2022 pm 07:08 PM

去掉重复并排序的方法:1、使用“Array.from(new Set(arr))”或者“[…new Set(arr)]”语句,去掉数组中的重复元素,返回去重后的新数组;2、利用sort()对去重数组进行排序,语法“去重数组.sort()”。

JavaScript的Symbol类型、隐藏属性及全局注册表详解JavaScript的Symbol类型、隐藏属性及全局注册表详解Jun 02, 2022 am 11:50 AM

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于Symbol类型、隐藏属性及全局注册表的相关问题,包括了Symbol类型的描述、Symbol不会隐式转字符串等问题,下面一起来看一下,希望对大家有帮助。

原来利用纯CSS也能实现文字轮播与图片轮播!原来利用纯CSS也能实现文字轮播与图片轮播!Jun 10, 2022 pm 01:00 PM

怎么制作文字轮播与图片轮播?大家第一想到的是不是利用js,其实利用纯CSS也能实现文字轮播与图片轮播,下面来看看实现方法,希望对大家有所帮助!

JavaScript对象的构造函数和new操作符(实例详解)JavaScript对象的构造函数和new操作符(实例详解)May 10, 2022 pm 06:16 PM

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于对象的构造函数和new操作符,构造函数是所有对象的成员方法中,最早被调用的那个,下面一起来看一下吧,希望对大家有帮助。

JavaScript面向对象详细解析之属性描述符JavaScript面向对象详细解析之属性描述符May 27, 2022 pm 05:29 PM

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于面向对象的相关问题,包括了属性描述符、数据描述符、存取描述符等等内容,下面一起来看一下,希望对大家有帮助。

javascript怎么移除元素点击事件javascript怎么移除元素点击事件Apr 11, 2022 pm 04:51 PM

方法:1、利用“点击元素对象.unbind("click");”方法,该方法可以移除被选元素的事件处理程序;2、利用“点击元素对象.off("click");”方法,该方法可以移除通过on()方法添加的事件处理程序。

整理总结JavaScript常见的BOM操作整理总结JavaScript常见的BOM操作Jun 01, 2022 am 11:43 AM

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于BOM操作的相关问题,包括了window对象的常见事件、JavaScript执行机制等等相关内容,下面一起来看一下,希望对大家有帮助。

foreach是es6里的吗foreach是es6里的吗May 05, 2022 pm 05:59 PM

foreach不是es6的方法。foreach是es3中一个遍历数组的方法,可以调用数组的每个元素,并将元素传给回调函数进行处理,语法“array.forEach(function(当前元素,索引,数组){...})”;该方法不处理空数组。

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)