使用child_process.exec发送返回404的命令

时间:2016-12-13 00:01:53

标签: javascript node.js express http-status-code-404 child-process

我有一个使用NodeJ的简单服务器设置,我想从中向服务器上的终端发送命令。

我尝试使用child_process.exec发送命令,当我从终端运行时,该命令正常工作。

我遇到的问题是找不到POST方法/ unLock。作为回应我得到了。

POST /unLock 404 1.770 ms - 1186

我已经包含了我在下面设置的服务器和路由/视图的代码,我是节点新手并尝试学习,所以任何帮助都将受到赞赏。

app.js

var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');

var index = require('./routes/index');
var users = require('./routes/users');
var exec = require('child_process').execSync;

var util = require('util')
//var exec = require('child_process').exec;
var app = express();

app.use( bodyParser.json() );       // to support JSON-encoded bodies
app.use(bodyParser.urlencoded({     // to support URL-encoded bodies
  extended: true
})); 
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');


app.get('/javascript/jquery.min.js', function (req, res) {
        res.sendFile( __dirname + "/javascript" + "/jquery.min.js" );

});

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', index);
app.use('/users', users);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

app.post('/', function(req, res) {
  console.log(req.body);
  res.send(200);

  });

//trying to send command here
//recieiving 404
app.post('/unLock', function (req, res) {
exec("ls -la", {stdio:[0,1,2]});
res.send(200);

console.log("button clicked");
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});


module.exports = app;

index.js

var express = require('express');
var router = express.Router();

router.get('/', function(req, res){
  res.render('index', {
    title: 'Home'
  });
});

router.get('/login', function(req, res){
  res.render('login', {
    title: 'login'
  });
});

router.get('/unLock', function(req, res){
    console.log("hello"); //this doesnt work 
});

router.get('/contact', function(req, res){
  res.render('contact', {
    title: 'Contact'
  });
});

module.exports = router;

index.ejs

<!DOCTYPE html>
<html>
<script language="JavaScript" type="text/javascript" src="/javascripts/jquery.min.js"></script>
<script>

function unLock() { 
  $.ajax({
    type: 'POST',
                url: '/unLock',
    data: '',
    success: function (data) {
                }
       });
}
//call button.js
</script>

  <head>
    <title><%= title %></title>
    <link rel='stylesheet' href='/stylesheets/style.css' />
  </head>
  <body>
    <h1><%= title %></h1>
    <p>Welcome to SecureLock - beta 1.0</p>
    <form><input type='button' value='unLock' onclick='unLock()'/></form>
  </body>

</html>

谢谢。

1 个答案:

答案 0 :(得分:1)

{-# LANGUAGE TypeFamilies #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE ExistentialQuantification #-} {-# LANGUAGE ConstraintKinds #-} class (Eq (UnMaybe a), a ~ Maybe (UnMaybe a)) => EqMaybe a where type UnMaybe a instance Eq a => EqMaybe (Maybe a) where type UnMaybe (Maybe a) = a data Test c = forall a. c a => Test a r :: Test EqMaybe -> Maybe Bool r (Test o) = (==) <$> o <*> o f :: Test Eq -> Test EqMaybe f (Test o) = Test (Just o) JS函数中,您使用方法 var syntaxTree = CSharpSyntaxTree.ParseText(File.ReadAllText("program.cs")); CSharpCommandLineArguments arguments = new CSharpCommandLineArguments(); arguments.Win32Icon = @"ICON PATH"; CSharpCompilation compilation = CSharpCompilation.Create( "program", new[] { syntaxTree }, new[] { MetadataReference.CreateFromFile(typeof(object).Assembly.Location) }, new CSharpCompilationOptions(OutputKind.ConsoleApplication)); ResourceWriter rs = new ResourceWriter("res.resources"); var resourceDescription = new ResourceDescription("program.Resources.resources", () => new MemoryStream(File.ReadAllBytes("res.resources")), true); using (var dllStream = new MemoryStream()) using (var pdbStream = new MemoryStream()) { var emitResult = compilation.Emit(dllStream, pdbStream, null,null, manifestResources: new [] {resourceDescription}); if (emitResult.Success) { File.WriteAllBytes("test.exe",dllStream.GetBuffer()); Console.WriteLine("compiled"); } else { Console.WriteLine("foutje: {0}", emitResult.Diagnostics[0].ToString()); } } Console.ReadLine(); 进行AJAX调用,但在您的路线中有

unLock()

所以没有回复POST的路线。将上面的行更改为router.get('/unLock', function(req, res){ ... }); 更改AJAX方法以键入POST。如果您实际上没有通过AJAX调用向服务器发送任何数据,则可能是后者。