简体   繁体   English

jquery ajax https 调用给出 ERR_INSECURE_RESPONSE

[英]jquery ajax https call gives ERR_INSECURE_RESPONSE

I'm trying to make a https CORS ajax call from jquery to a node.js process.我正在尝试从 jquery 到 node.js 进程进行 https CORS ajax 调用。 However When ever the call is made chrome complains in the console OPTIONS https://localhost/ net::ERR_INSECURE_RESPONSE .但是,当调用时,chrome 会在控制台OPTIONS https://localhost/ net::ERR_INSECURE_RESPONSE中抱怨。

Looking at a similar stack overflow question, Cross domain request from HTTP to HTTPS aborts immediately I should be able to make cross origin https ajax calls if I import the self signed cert I made.查看类似的堆栈溢出问题, 从 HTTP 到 HTTPS 的跨域请求立即中止如果我导入我制作的自签名证书,我应该能够进行跨源 https ajax 调用。 So I imported the cert into chrome.所以我将证书导入到 chrome 中。 I can see the certificate in chrome's manage certificates tab under Authorities.我可以在 chrome 的“管理证书”选项卡中看到该证书。 But it still fails when I try the ajax call.但是当我尝试ajax调用时它仍然失败。

This is how I made the private key: openssl genrsa -out domain.key 4096这就是我制作私钥的方式: openssl genrsa -out domain.key 4096

Now the cert: openssl req -x509 -sha512 -nodes -newkey rsa:4096 -keyout domain.key -out domain.crt现在证书: openssl req -x509 -sha512 -nodes -newkey rsa:4096 -keyout domain.key -out domain.crt

For common name I put the IP address of the computer so chrome would not complain about a URL mismatch.对于通用名称,我输入了计算机的 IP 地址,因此 chrome 不会抱怨 URL 不匹配。

Here is the html page.这是html页面。

<!DOCTYPE html>
<html>
  <title>BlackBox</title>
  <head>
    <meta charset="utf-8">
    <script src="jquery-1.11.2.min.js"></script>
    <script src="bootstrap-3.3.4-dist/js/bootstrap.min.js"></script>
    <script src="login.js"></script>
  </head>
  <body>
    <div class="container-fluid">
      <div class="row">
        <div class=col-md-4>
          <h2> Welcome to BlackBox</h2>
          <label>username</label>
          <input type="text" name="username" id="username">
          <label>password</label>
          <input type ="text" name="password" id="password">
          <input type="button" id="loginbtn" value="Login"/>
          <div class="container">
            <div class="row">
              <div class="out"></div>
            </div>
          </div>
        </div>
      </div>
     </div>
   </body>
 </html>

This is the javascript that goes along with the html.这是与 html 一起使用的 javascript。

 $(document).ready(function() {
   $('#loginbtn').click(clickLogin);
     function clickLogin() {
       var username = $('#username').val();
       var password = $('#password').val();
       if(password == '' || username == '') {
         $(".out").html("Empty username or password");
         } else {
         $.ajax({
           type: "PUT",
           url: "https://localhost/",
           contentType: "application/json",
           data: JSON.stringify({
             username: username,
             password: password,
           }),
           dataType: "text",
       })
     }
   };
 });

And finally here is the node process that both serves the html and javascript and is suppose to receive the ajax calls.最后是节点进程,它同时为 html 和 javascript 提供服务,并假设接收 ajax 调用。

const fs = require("fs");
const http = require('http');
const https = require('https');

var loginPage = fs.readFileSync('login.html');
var loginPageJs = fs.readFileSync('login.js');
var jquery = fs.readFileSync('jquery-1.11.2.js');
var bootstrap = fs.readFileSync('bootstrap-3.3.4-dist/js/bootstrap.min.js')

var options = {
  key: fs.readFileSync('domain.key'),
  cert: fs.readFileSync('domain.crt')
};

http.createServer(function(req, res) {  
  res.writeHead(301, {Location: 'https:192.168.1.58/'})
  res.end();
}).listen(80);

https.createServer(options, function(req, res) {

  if(req.method === 'GET' && req.url === '/') {
  res.writeHead(200, "OK", {'Content-Type': 'text/html'});
  res.write(loginPage);
  res.end();
} else if(req.method === 'GET' && req.url === '/login.js') {
  res.writeHead(200, "OK", {'Content-Type': 'application/javascript'});
  res.write(loginPageJs);
  res.end();
} else if(req.method === 'GET' && req.url === '/jquery-1.11.2.js') {
  res.writeHead(200, "OK", {'Content-Type': 'application/javascript'});
  res.write(jquery);
  res.end();
} else if(req.method === 'GET' && req.url === '/bootstrap-3.3.4-     dist/js/bootstrap.min.js') {
  res.writeHead(200, "OK", {'Content-Type': 'application/javascript'});
  res.write(bootstrap);
  res.end();
} else if(req.method === "OPTIONS" && req.url === '/') {
  res.writeHead(204, "No Content", {
    "access-control-allow-origin": origin,
    "access-control-allow-methods": "GET, POST, PUT, DELETE, OPTIONS",
    "access-control-allow-headers": "content-type, accept",
    "access-control-max-age": 10,
    "content-length": 0
  });

  var requestBodyBuffer = [];

  req.on("data", function(chunk) {
    requestBodyBuffer.push(chunk);
  })

  req.on("end", function() {
    var requestBody = requestBodyBuffer.join("");
    var obj = JSON.parse(requestBody);
    if(obj.hasOwnProperty('username') && obj.hasOwnProperty('password'))  {
      console.log(obj.username);
      console.log(obj.password);
    }
  })
 }

}).listen(443);

Recently I write an app for whois lookup and I had this problem too,but finally after checking all possibilities , it worked correctly.最近我写了一个用于 whois 查询的应用程序,我也遇到了这个问题,但最后在检查了所有可能性之后,它工作正常。

this is a helpful article for generating self-signed certificates :这是一篇有助于生成自签名证书的文章:

https://www.digitalocean.com/community/tutorials/openssl-essentials-working-with-ssl-certificates-private-keys-and-csrs https://www.digitalocean.com/community/tutorials/openssl-essentials-working-with-ssl-certificates-private-keys-and-csrs

*** Comment's In Code Will Help You **** *** 代码中的注释将帮助您 ***

index.js Code : index.js 代码:

 function checkAvailability(domainParsed) {

        $.ajax({
            method : "GET",
            url : "https://localhost:55555/check", // Pay attention To This Line 
                            "Content-Type" : "application/json",
            data : {domain : domainParsed , array : postFixesArray } 

            }).done(function(data) {
                    availableDomanisToShow = data.availableDomains;
                    registeredDomanisToShow = data.registeredDomains;
            });

    }

server.js Code : server.js 代码:

var bodyParser = require("body-parser") ;
var unirest = require('unirest');
var https = require('https');
var http = require('http');
var fs = require('fs');
var express = require('express');
var app = express();

var registeredDomains = [];
var availableDomains = [];
var counter = 0 , i = 0;

app.use(bodyParser.json({ type: 'application/json'})) ;
app.use(bodyParser.urlencoded({ extended:true })) ;

app.use(function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*"); // Pay attention To This Line --> Cross domain request
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept"); // Pay attention To This Line --> Cross domain request
    next();
});

app.use("/check",function(req,resp,next) {

   var fqdn,postfix;

   availableDomains = [];
   registeredDomains = []

   while( i < req.query.array.length) {
            fqdn = req.query.domain + req.query.array[i];
            postfix = req.query.array[i];
            checkAvailability(fqdn,postfix,req.query.array.length);
            console.log(req.query.array.length)
            i++;
   }

   function checkAvailability(domain,postfix,length) {
        unirest.get('https://jsonwhois.com/api/v1/whois').headers({
                'Accept': 'application/json',
                'Authorization': 'Token token=238d7da7fac57882a176cb14411d781a'
            }).query({
                "domain" :  domain
            }).end(function(response) {
                console.log(domain , response.body['available?']);
                if(true != response.body['available?']) {
                    registeredDomains.push(postfix);
                    counter++;
                    if(counter == length) {
                            counter = 0 ;
                            i = 0;
                            resp.json( { "registeredDomains" : registeredDomains , "availableDomains" : availableDomains } );                   
                    }
                }
                else  {
                    availableDomains.push(postfix);
                    counter++;
                    if(counter == length) {
                            counter = 0 ;
                            i = 0;
                            resp.json( { "registeredDomains" : registeredDomains , "availableDomains" : availableDomains } );
                    }
            }
       });
    }
});



 https.createServer({
  key: fs.readFileSync('key.pem'),
  cert: fs.readFileSync('cert.pem')
 }, app).listen(55555);

 http.createServer(app).listen(8000);
 console.log("httpsServer are Listening on " + 55555);
 console.log("httpServer are Listening on " + 8000);

For testing/development purpose you can also just disable chromium security出于测试/开发目的,您也可以禁用铬安全性

run chromium / google chrome with the following arguments, replace user-data-dir with you chrome directory or with /tmp if you just need a one shot configuration使用以下参数运行 chromium / google chrome,将 user-data-dir 替换为您的 chrome 目录或 /tmp 如果您只需要一次性配置

chromium-browser --allow-running-insecure-content --disable-web-security --user-data-dir=~/.config/chromium/Default

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM