Let you learn knowledge clearly, there are codes, there are explanations, copy of the walk, learn will!

What we have worked so hard to write, someone else’s simple iframe, decorated on the outside, suddenly changed into his, how to prevent this direct theft of others’ achievements behavior

Today we will learn about the X-frame-options response header in HTTP. The purpose of this response header is to prevent site hijacking

Go straight to the code and see what happens

The app.js and frame-Content-refuse. Js codes are the same except that the listening port is different from the following

App.js does not contain the following, frame-Content-refuse. Js adds this response header setting

app.use((req, res, next)=> {
  res.set('X-Frame-Options'.'DENY')
  next()
})
Copy the code

Frame – content – refuse. Js file

Const express = require(const express = require('express')
const path = require("path")
const logger = require('morgan')
const chalk = require('chalk')
const app = express()
const router = express.Router()
app.use(logger('dev'))
app.use((req, res, next)=> {
  res.set('X-Frame-Options'.'DENY')
  next()
})
app.use(express.static(path.join(__dirname, 'public')))
app.use(router)
app.listen(3010, () => {
  console.log(`http://localhost:3010`, chalk.red('Demo content should not be displayed in iframe'))})Copy the code

Now for port 3000, add an iframe to embed the port 3010 page

The front-end code

<h3> uses iframe to load content that does not meet the same origin policy </h3> <div> Below is port 3010test-content.html
  </div>
  <iframe src="http://localhost:3010/test-content.html" width="400" height="200" frameborder="0"></iframe> <div> loads a content of the same origin -- below for port 3000test-content.html
  </div>
  <iframe src="http://localhost:3000/test-content.html" width="400" height="200" frameborder="0"></iframe>
Copy the code

Effect of the bar, directly refused white piao

Look again at the response header returned by the 3010 service

The response status code is still 200, but it doesn’t give you anything back. That’s what x-frame-options is for. There is also an option, as long as there is cross-domain (protocol version + domain name + port), DENY works the same as SAMEORIGIN

SAMEORIGIN: indicates the restriction of the same-origin policy. DENY indicates a direct denial

Refuse white piao, start from me, point 👍👍👍 bai!