nodejs accepts parameters from the front end and returns data

nodejs accepts the parameters from the front end and returns data
1. Requirements analysis
​ The front end sends a parameter, then uses nodejs as the back end to receive it, and returns the data to the front end

2. Implementation steps
The backend is implemented with nodejs, and data is processed by setting an interface. There
must be cross-domain problems in data transmission. Here, cross-domain problems are handled through cors.
The front-end passes parameters to the interface through Ajax

Create a new shell_send.js

var express = require('express');
var app = express();
var process = require('child_process');

app.all("*", function (req, res, next) {
	//设置允许跨域的域名,*代表允许任意域名跨域
	res.header("Access-Control-Allow-Origin", "*");
	//允许的header类型
	res.header("Access-Contro1-Allow-Headers", "content-type");
	//跨域允许的请求方式
	res.header("Access-Control-Allow-Methods", "DELETE,PUT,POST,GET,OPTIONS");
	if (req.method.toLowerCase() == 'options ')
		res.send(200);//让options尝试请求快速结束else
	next();
})

app.get('/api', function (req, res) {
    res.send('OK');
    console.log(req.query.a);
    process.exec(`/bin/sh send.sh true "@${req.query.a}"`,function (error, stdout, stderr) {
        if (error !== null) {
            console.log('exec error: ' + error);
        }
    });
})
 
var server = app.listen(8083, function () {
    var host = server.address().address
    var port = server.address().port
})

Create a send.html file

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>通知</title>
</head>
<body>
    <textarea name="aaa" id="aa" cols="30" rows="10"></textarea>
    <button>点击发送</button>
</body>
</html>
<script>
    let a = document.getElementById("aa");
    let btn =  document.querySelector("button");
    
    //点击按钮发起Ajax请求,并将textarea中的内容作为参数传递
    btn.onclick = function(){
        let xhr = new XMLHttpRequest();
        xhr.open("get","http://10.0.0.203:8083/api?a="+a.value);
        xhr.send();
        xhr.onload = function(){
            console.log(xhr.responseText);
        }
    }
</script>

Five, run

  1. Run the shell_send.js file in node, and run the command as node shell_send.js
  2. Open the send.html file, write the content test123, and click the send button
  3. You can see it in the console, and the sent information will be received in node

 

Guess you like

Origin blog.csdn.net/leonnew/article/details/124803009