http/https + nodejs responds to http and https requests at the same time (with SSL certificate application)

foreword

The Https protocol implements data encryption on the basis of the Http protocol . Therefore, when using the HTTPS protocol to request access, you must have an SSL certificate (for the application process, please refer to SSL certificate application ). This article mainly talks about building a simple server to receive http and https requests.

1. Import the SSL certificate into the project

Tip: Even if you don't have an SSL certificate , the following code will help you. Especially the sixth part is very practical in project development.

1. We will rename the downloaded SSL certificate (including modifying the suffix, the application process can refer to SSL certificate application ), the private key file is named private.key , and the certificate file is named file.crt . Then copy these two files to the project, the directory structure is as follows (for reference only, you can create directories freely).
insert image description here
2. You can see that there are several files in the above directory. We mainly talk about router.js, app.js and server.js . The core part is the server.js file. I hope to read it in order. Files like node_modules, package-lock.json and package.json need the modules required by npm , and nodeJs will be used. If you don’t know it, you can visit Simple Construction of NodeJs Server or NodeJs Tutorial to learn about it. It’s very simple.

Note: All the code of this blog post can be copied directly. If there is an error that a certain module does not exist, you need the corresponding module of npm .

2. router.js

'use strict'
var express = require('express')		// 记得npm 'express' 模块
var router = express.Router()

var value = "1"
router.get("/", function(req, res, next){
    
    
	res.send("/")
})

router.get("/setValue", function(req, res, next){
    
    
	// 获取key - value
	var keys = Object.keys(req.query)
	
	// 以返回第一个参数为例
	value = req.query[keys[0]]
	
	// 简单处理一下value 
	value = value || {
    
    value:null}
	res.send(value)
})

router.get("/getValue", function(req, res, next){
    
    	
	// 有上述的set,怎么也得有个配套的get
	res.send(value)
})

module.exports = router

3. app.js

'use strict'
var express = require("express")
var path = require("path")
var cookieParser = require('cookie-parser')		// 记得npm 'cookie-parser' 模块
var bodyParser = require('body-parser')			// 记得npm 'body-parser' 模块
var router = require("./router")
var app = express()

app.all("*", function(req, res, next){
    
    
	res.header('Access-Control-Allow-Origin', '*')
	res.header('Access-Control-Allow-Headers', 'Content-Type, Content-Length, Authorization, Accept, X-Requested-With , yourHeaderFeild')
	res.header('Access-Control-Allow-Methods', 'PUT, POST, GET, DELETE, OPTIONS')
	
	if (req.method == 'OPTIONS') 
		res.send(200) /*让options请求快速返回*/
	else 
		next()
})

app.use(bodyParser.json())
app.use(bodyParser.urlencoded({
    
    extended: false}))
app.use(cookieParser())
app.use("/", router)

module.exports = app

4. server.js

'use strict'
var fs = require('fs')
var path = require('path')
var http = require('http')
var https = require('https')
var app = require('./app')

//检测端口号是否合法
var normalizePort = function(val)
{
    
    
	var port = parseInt(val, 10)
	
	if(isNaN(port))
		return val

	if(port >= 0)
		return port

	return false
}

// 获取ssl证书所在的路径
var ssl_path = path.resolve(__dirname, '.') + '/ssl'

// 将ssl证书配置在对象内
var credentials = {
    
    
  key: fs.readFileSync( ssl_path + '/private.key', 'utf8'),
  cert: fs.readFileSync(ssl_path + '/file.crt', 'utf8')
}

// 创建https, 端口号是8080 (如果端口号不能用,需要查看设置是否被拦截或不信任)
var https_port = normalizePort('8080')
var https_server = https.createServer(credentials, app)
https_server.listen(https_port)

// 创建http,端口号是8000 (如果端口号不能用,需要查看设置是否被拦截或不信任)
var http_port = normalizePort('8000')
var http_server = http.createServer(app)
http_server.listen(http_port)

5. Execution Results

1. Open the terminal, cd to the directory where server.js is located, press Enter, then enter the command node server.js and press Enter, and this simple server will start running. If some errors such as the module does not exist are reported, you need to npm the module. If it runs successfully, there is no output, as shown in the figure below.
insert image description here
2. We enter different URLs to compare.
(1) Enter the URL http://localhost:8000/setValue?&age=18 , and a 18 will be displayed on the web page .
(2) Enter the URL http://localhost:8080/setValue?&age=18 , but the webpage cannot be opened normally .
(3) Enter the URL https://localhost:8080/setValue?&age=18 , and a 18 will be displayed on the web page .
(4) Enter the URL https://localhost:8000/setValue?&age=18 , but the webpage cannot be opened normally .

Through the above four comparisons, we can know that in the same server, both http requests and https requests are monitored, but different protocols can only access the corresponding ports, otherwise the access fails.
3. We are entering the URL https://localhost:8000/getValue , and a 18 is displayed on the webpage .

Access to the server through the web page has been completed. But in actual development, we can't access everything through the web page. Next, let's find out how to use code to access the above-mentioned server in the project.

6. Client code access server

1. The above content is only a simple operation on the web page, and it is not very practical in the project. Next, let’s talk about practical development content. We create a file named request_server.js and edit the content as follows (the code can be copied directly):

var request_server = 
{
    
    
    value:0,    
    request_server_value : function()
    {
    
    
        var xmlhttp = null
        if(window.XMLHttpRequest)
            xmlhttp = new XMLHttpRequest()
        else
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP")
	
		// 在 onreadystatechange 调用该 callback,该函数在下面
        var callback = function(ret, data)
        {
    
    
            if(ret)
            {
    
    
            	// 对数据做些简单的处理
            	// 该示例在请求访问时,传递的参数是可转义的类型,如 "1"和1, 如果是其他类型,可以自行修改下述两行代码
                var _value = typeof(data) == 'object' ? '0':data
                https_request.value = parseInt(_value)
	
				// 打印一下访问到的结果
                console.log(">>>> value is ", https_request.value)
                try{
    
    

                }catch(e){
    
    

                }
            }
            else
                https_request.value = 0
        }

        xmlhttp.onreadystatechange = function()
        {
    
    
            if(xmlhttp.readyState == 4)
                callback?callback(xmlhttp.status==200, xmlhttp.responseText):''
        }
	
		// 做本地访问操作,localhost 可以是你的远超服务端的 ip地址 或 域名
        xmlhttp.open("GET", 'https://localhost:8080/getValue', true)
        xmlhttp.setRequestHeader("Content-Type", "application/json; charset=UTF-8");
        xmlhttp.send()
    },
}

2. Then we put the request_server.js file into the project. As for me, I made a simple button for testing, and its callback function is click_callback() , the code is as follows:

click_callback: function ()
{
    
    
	// 点击按钮时,调用 request_server_value 函数
    request_server.request_server_value()
}

The function of this button can only be completed by yourself. There are many types of clients, and it is not clear at the moment.
Click the button and open the console of the editor, and find that the received data is 18, then this is successful.
insert image description here
All the explanations are over, I hope it will be helpful to you.

おすすめ

転載: blog.csdn.net/HYNN12/article/details/107231233