油猴发跨域请求

3,100 阅读1分钟

本想使用fetch,设置mode为no-cors也不行。

使用ajax

function postData(url, data) {
  return new Promise(function(resolve, reject) {
    const xhr = new XMLHttpReqeust();
    xhr.open('POST', url, true);
    xhr.setRequestHeader('Content-Type', 'application/json;charset=UTF-8');
    xhr.send(JSON.stringify(data));
    xhr.onreadystatechange = function() {
      if (xhr.readyState === 4) {
        if (xhr.status === 200) resolve(xhr.responseText);
        else reject(xhr.status);
      }
    };
  });
}

本想在油猴中发跨域请求,结果报错XMLHttpRequest不存在。

需要使用油猴提供的GM_xmlhttpRequest();

使用前需要先进行授权: // @grant GM_xmlhttpRequest

function postData(url, data) {
  return new Promise(function(resolve, reject) {
    GM_xmlhttpRequest({
      method: 'POST',
      url,
      headers: {
        'Content-Type': 'application/json;charset=UTF-8'
      },
      data: JSON.stringify(data),
      onload(xhr) {
        resolve(xhr.responseText);
      }
    }); 
  });
}

注意:使用GM_xmlhttpRequest()发送的请求不会出现在dev tools的Network中。

在node express下设置cors

before(app) {
  app.use('*', function(req, res, next) {
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Methods', 'GET,POST,OPTIONS');
    res.header('Access-Control-Allow-Headers', 'Content-Type');
    res.header('Access-Control-Allow-Credentials', 'true');
    if (req.method === 'OPTIONS') {
      res.sendStatus(200);
    } else next();
  });
}