Node.js ajax data request cross domain problem

Recently, I wanted to use node as the background to throw the interface. When the front-end page went to request the interface, an error was reported, and it was found that it was a cross-domain problem. Why do cross-domain problems occur? We need to understand what is the browser's same-origin policy.
What is the browser's same-origin policy and why

In simple terms, the same-origin policy is three identical, the same protocol, the same domain name, and the same port. Scripts in a domain only have permissions in this domain, so it can be understood that scripts in this domain can only read and write resources in this domain, but cannot access resources in other domains. This security restriction is called the same-origin policy. The reason for the same-origin policy is to improve the security of the browser. However, we all know that security and convenience are inversely proportional, and high security will definitely give us The operation brings inefficiency at the expense of flexibility in Web expansion, and modern browsers choose a balance between security and usability. On the basis of following the same-origin policy, the backdoor is selectively "opened" for the same-origin policy. For example, tags such as img, script, style, etc., allow subdomains to reference resources. Strictly speaking, this does not meet the same-origin requirement.

This security policy of JavaScript is particularly important in multi-iframe or multi-window programming, as well as Ajax programming. According to this policy, the JavaScript code contained in the page under souhu.com cannot access the content of the page under the google.com domain name; even pages between different subdomains cannot access each other through JavaScript code. The impact on Ajax is that Ajax requests implemented through XMLHttpRequest cannot submit requests to different domains. For example, pages under you.example.com cannot submit Ajax requests to me.example.com, and so on.

for example
URL illustrate Whether to allow communication
http://www.baidu.com/a.js
http://www.baidu.com/b.js
same domain name allow
http://www.baidu.com/map/a.js
http://www.baidu.com/tieba/b.js
Different folders under the same domain name allow
http://www.baidu.com:8000/a.js
http://www.baidu.com/b.js
Same domain name but different ports not allowed
http://www.baidu.com/a.js
https://www.baidu.com/b.js
Different protocols for the same domain name not allowed
http://www.baidu.com/a.js
http://75.32.68.45/b.js
Domain name and domain name corresponding to ip not allowed
http://www.baidu.com/a.js
http://query.baidu.com/b.js
The main domain is the same, the subdomains are different not allowed
http://www.baidu.com/a.js
http://www.google.com/b.js
different domain names not allowed
Why do browsers implement the same-origin restriction? Let's give an example:

For example, a hacker uses iframe to embed the real bank login page on his page. When you log in with a real username and password, if there is no same-origin restriction, his page can read your form through javascript In this way, the user name and password can be easily obtained. Another example is that you log in to Taobao and browse a malicious website at the same time. If there is no same-origin restriction, the malicious website can construct AJAX requests to frequently post advertisements on Taobao.

This is the error displayed by the front page
//前端页面报错内容
Failed to load http://localhost:3000/users/login: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost' is therefore not allowed access.
//服务端错误方法
// node登录接口,文件地址routes/users.js
router.post('/login',function (req, res, next) {
    // 打印post请求的数据内容
    console.log(req.body);
    console.log(req.body.username);
    console.log(req.body.password);
    if (req.body.username == "shuah" && req.body.password == "123456") {
        res.end(JSON.stringify(dataSuccess));
    } else {
        res.end(JSON.stringify(dataError));
    }
});
//前端数据请求
//引用jquery.js
var data ={
      username:'shuah',
      password:'123456'
}
$.ajax({
  url: "http://localhost:3000/users/login",
  type: "POST",
  headers:{
    "Conten-Type":"http://localhost:3000/users/login"
    },
  data: JSON.stringify(data),
  dataType:"json",
  success: function(data){
    console.info("success.");
    console.log(data)
  }
})

Two methods for solving node cross-domain are summarized.

  1. Simple and rude, but any page can be requested, not safe.
//在每个方法的头部加入
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "X-Requested-With");
res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
res.header("X-Powered-By",' 3.2.1');
res.header("Content-Type", "application/json;charset=utf-8");
// login 方法修改为
router.post('/login',function (req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "X-Requested-With");
  res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
  res.header("X-Powered-By",' 3.2.1');
  res.header("Content-Type", "application/json;charset=utf-8");
  // 打印post请求的数据内容
  console.log(req.body);
  console.log(req.body.username);
  console.log(req.body.password);
  if (req.body.username == "shuah" && req.body.password == "123456") {
      res.end(JSON.stringify(dataSuccess));
  } else {
      res.end(JSON.stringify(dataError));
  }
});
//前端页面
$.ajax({
  url: "http://localhost:3000/users/login",
  type: "POST",
  data:data,
  dataType:"json",
  success: function(data){
      console.info("success.");
      console.log(data)

  }
})

2. Introduce cors security, custom

npm install cors

The github address of cors, there are more methods in it https://github.com/expressjs/cors

//相对与上一个方法,这个不用每个方法都添加请求头
//在app.js里面修改
var cors = require('cors')
app.use(cors())
//自定义设置
//在app.js里面修改,只有http://localhost可以访问请求,其他都为跨域,安全,需要启动一个本地服务
var cors = require('cors')
app.use(cors({
    origin:['http://localhost'],
    methods:['GET','POST'],
    alloweHeaders:['Conten-Type', 'Authorization']
}));

//前端页面
$.ajax({
  url: "http://localhost:3000/users/login",
  type: "POST",
  data:data,
  dataType:"json",
  success: function(data){
    console.info("success.");
    console.log(data)
  }
})

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325509488&siteId=291194637
Recommended