下面是文件夹结构:
我试图让我的Python脚本从我的HTML文件中获取输入,并给予它的输出显示的HTML
以下是jQuery中的html脚本:
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function () {
$("#submit_SF").click(function () {
var userChoice = $("#score_function").val();
$.ajax({
url: "/runSF",
method: "POST",
data: { choice: userChoice },
success: function (data) {
$("#tableData").html(data);
}
});
});
});
</script>
下面是我的app.js
文件:
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var bodyParser = require('body-parser');
var { spawn } = require('child_process');
// Define route var
var indexRouter = require('./routes/index');
var fsRouter = require('./routes/fs');
var usersRouter = require('./routes/users');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
// Define route
app.use('/', indexRouter);
app.use('/fs', fsRouter);
app.use('/users', usersRouter);
// catch 404 and forward to error handler
app.use(function (req, res, next) {
next(createError(404));
});
// 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;
app.use(bodyParser.urlencoded({ extended: false }));
app.use(express.static('public'));
app.post("/runSF", (req, res) => {
const userChoice = req.body.choice;
console.log("Received POST request with user choice:", userChoice);
// Run the Python script with the user's choice as an argument
const pythonProcess = spawn('python', ['SFscript.py', userChoice]);
pythonProcess.stdout.on('data', (data) => {
// Send the Python script's output back to the client
const outputData = data.toString();
console.log("Python script output:", outputData); // Log script output
res.send(outputData);
});
pythonProcess.stderr.on('data', (data) => {
console.error("Error executing Python script:", data); // Log script errors
});
});
当我点击html按钮时,浏览器控制台会显示以下内容:
jquery-3.6.0.min.js:2 POST http://localhost:3000/runFS 404 (Not Found)
send @ jquery-3.6.0.min.js:2
ajax @ jquery-3.6.0.min.js:2
(anonymous) @ fs:50
dispatch @ jquery-3.6.0.min.js:2
v.handle @ jquery-3.6.0.min.js:2
我觉得这很容易修复,但我对node.js的了解还不够。
我不知道该尝试什么,这个app.post("/runFS", (req, res) => {});
不应该足以配置路由吗?
请随意请求我没有显示的任何其他文件。先谢谢你了
1条答案
按热度按时间yhuiod9q1#
您需要将
app.post("/runSF"
路由移动到处理和调用next(createError(404));
的路由之上。所以这个:看起来你是在你的
app.post("/runSF"
可以达到之前创建的404。以下代码行也是冗余的:
那是因为你已经在文件顶部附近调用了它们: