


[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 aAt this time, someone will Go up and recommendtxt
(or
pdf/'json', etc.) file download
url, but when I open it with the
atag, it turns into a preview... What should I do? Save!!!"
FileSaver.js or "Save handwritten reading stream as".
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.
Content-Disposition: inline
At this time, the message body will be part of the page or Displayed in the form of the entire page. (Preview)
Content-Disposition: attachment
The message body should be downloaded, and the default file name is related to the
urlformat.
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##1.3 ExampleContent-Type
for consumption;
To this end, I specially wrote a
express small example. I probably wrote three routes under the
application, as follows: <div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false">const user = {
name: "摸鱼的春哥",
blogUrl: "https://juejin.cn/user/1714893870865303"
}
const contentDispositionInline = async (req, res, next) => {
res.setHeader('Content-Disposition', 'inline')
res.send(user)
}
const contentDispositionFilename = async (req, res, next) => {
res.setHeader('Content-Disposition', 'attachment; filename="chunge.json"')
res.send(user)
}
const contentDispositionNoFilename = async (req, res, next) => {
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:
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
. Don't attribute your problem to browser cache either.
Browser cachewas 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.
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 "Brother Chun, why is it that my login is successful but the request is still "Brother Chun, why can't I get the value I deposited into " Brother Chun, Brother Chun, is this Me: "Brother, do you have it? Have you ever heard of a response header called That’s it! That's it! that's it! All kinds of anomalies about And the These features include: 401 Cookie ", if there is no problem on the server side, it is probably that the , and you are not the same person as the last login. If you are in a environment, you may need to temporarily remove the is subject to domain restrictions 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 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.
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=
.
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?
hash
value can be strongly cached.
(After all, once the content changes, the hash
of the name will also change) cdn
, which can also enable strong caching.
(For example, /xx/xx/jquery.min.js
switches to jquery@3.6.0/dist/jquery.min.js
) 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
401
?" cookie
?"cookie
broken? It’s obviously valuable in the browser, why can’t I access it?"set-cookie
?”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. 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.
Expires=<date></date>
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=<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-value></path-value>
is a more detailed control strategy than Domain
, and even specifies
Cookie can be sent only under the xx
path. 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. js
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
. 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
: cross-domain is also allowed, no restriction.
3.3 Analysis of Development Frequently Asked Questions
web front-end?
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
browser does not actually store Cookie
. In other words, every time you initiate a request, the server thinks that you are a Secure
attribute.
, Whether there are path restrictions , Are there HttpOnly?
Check one by one Come down, the problem is not difficult to solve.
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



Vue.js is suitable for small and medium-sized projects and fast iterations, while React is suitable for large and complex applications. 1) Vue.js is easy to use and is suitable for situations where the team is insufficient or the project scale is small. 2) React has a richer ecosystem and is suitable for projects with high performance and complex functional needs.

Using Bootstrap in Vue.js is divided into five steps: Install Bootstrap. Import Bootstrap in main.js. Use the Bootstrap component directly in the template. Optional: Custom style. Optional: Use plug-ins.

You can add a function to the Vue button by binding the button in the HTML template to a method. Define the method and write function logic in the Vue instance.

There are three ways to refer to JS files in Vue.js: directly specify the path using the <script> tag;; dynamic import using the mounted() lifecycle hook; and importing through the Vuex state management library.

The watch option in Vue.js allows developers to listen for changes in specific data. When the data changes, watch triggers a callback function to perform update views or other tasks. Its configuration options include immediate, which specifies whether to execute a callback immediately, and deep, which specifies whether to recursively listen to changes to objects or arrays.

Vue multi-page development is a way to build applications using the Vue.js framework, where the application is divided into separate pages: Code Maintenance: Splitting the application into multiple pages can make the code easier to manage and maintain. Modularity: Each page can be used as a separate module for easy reuse and replacement. Simple routing: Navigation between pages can be managed through simple routing configuration. SEO Optimization: Each page has its own URL, which helps SEO.

Vue.js has four methods to return to the previous page: $router.go(-1)$router.back() uses <router-link to="/" component window.history.back(), and the method selection depends on the scene.

You can query the Vue version by using Vue Devtools to view the Vue tab in the browser's console. Use npm to run the "npm list -g vue" command. Find the Vue item in the "dependencies" object of the package.json file. For Vue CLI projects, run the "vue --version" command. Check the version information in the <script> tag in the HTML file that refers to the Vue file.
