繁体   English   中英

在 URL 上使用 sh 脚本发送带有指定查询参数的节点 js 服务器请求

[英]Using a sh script to send node js server requests with specified query parameters on the URL

我现在对如何开始我当前的项目有点迷茫。 我真的只是需要一些帮助才能让它开始,我应该能够从那里得到它。 我对 JavaScript、php 和 mysql 有一些经验,但在节点 js 中几乎没有。

我有一个看起来像这样的 .sh 脚本文件:

curl localhost:3000/signup?user=jack\&height=6\&time=0
curl localhost:3000/arm?left=0.000000\&right=0.000000\&time=0 --cookie "USER=jack"
curl localhost:3000/echo?dist=9.220000\&time=10 --cookie "USER=jack"
curl localhost:3000/line?l1=1\&l2=1\&l3=1\&time=20 --cookie "USER=jack"
curl localhost:3000/other?ir=0\&time=30 --cookie "USER=jack"

我想在 shell 中使用这些指定的查询参数发送我的节点 js 服务器请求,但我不知道该怎么做。 到目前为止,这是我的节点 js 代码:

const { exec } = require('child_process');
var script = exec('myscript.sh' ,
        (error, stout, stderr) => {
           console.log(stdout);
           console.log(stderr);
           if ( error !== null ) {
              console.log(`exec error: ${error}`);
            }
        });

var http = require('http');
var url = require('url');

http.createServer(function(req, res) {
          var q = url.parse(req.url, true).query;
          res.writeHead(200, {'Content-Type' : 'text/html'});
          res.end("user " + q.first + " height " + q.second);
       }).listen(3000);

当我 go 到 localhost:3000 时,我可以看到“用户未定义的高度未定义”,当我在命令行中键入“node file.js”时,我得到脚本开始回显 linux 命令行中的每一行......但是如何我把两者放在一起吗? 我将如何解析脚本或使用该脚本将我需要的请求发送到我的节点 js 服务器? 我真的不知道从哪里开始这个项目。 使用 php 和 mysql 会更容易吗? 感谢您对此提供的任何帮助。 谢谢。

您必须等待 http 服务器才能向它发出请求:


const http = require('http');
const url = require('url');
const { exec } = require('child_process');


// create http server
const server = http.createServer(function (req, res) {

    // parse query parameter
    var q = url.parse(req.url, true).query;

    // write http header to client
    res.writeHead(200, {
        'Content-Type': 'text/html'
    });

    // send back body repsonse
    res.end("user " + q.first + " height " + q.second);

});


// wait for the http server to start
server.on("listening", () => {

    // do requests to the defined http server above
    const script = exec('myscript.sh', (error, stout, stderr) => {

        console.log(stdout);
        console.log(stderr);

        if (error) {
            console.log(`exec error: ${error}`);
        }

    });

});

server.listen(3000);

不要忘记使 your.sh 脚本可执行chmod +x myscript.sh

#!/bin/bash
curl "http://localhost:3000/signup?user=jack&height=6&time=0"
curl "http://localhost:3000/arm?left=0.000000&right=0.000000&time=0" --cookie "USER=jack"
curl "http://localhost:3000/echo?dist=9.220000&time=10" --cookie "USER=jack"
curl "http://localhost:3000/line?l1=1&l2=1&l3=1&time=20" --cookie "USER=jack"
curl "http://localhost:3000/other?ir=0&time=30" --cookie "USER=jack"

暂无
暂无

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

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