我试图创建一个端点 API,当通过我的 PHP 网站发送发布请求时,它会在托管 Express 应用程序的服务器上本地更新文件。
我在发送表单数据时遇到错误...
报错如下: API错误:
Error: Invalid request data
at Settings.handleSettingsRequest (/root/API/index.js:264:19)
at Layer.handle [as handle_request] (/root/API/node_modules/express/lib/router/layer.js:95:5)
at next (/root/API/node_modules/express/lib/router/route.js:144:13)
at Route.dispatch (/root/API/node_modules/express/lib/router/route.js:114:3)
at Layer.handle [as handle_request] (/root/API/node_modules/express/lib/router/layer.js:95:5)
at /root/API/node_modules/express/lib/router/index.js:284:15
at Function.process_params (/root/API/node_modules/express/lib/router/index.js:346:12)
at next (/root/API/node_modules/express/lib/router/index.js:280:10)
at requestHandler (/root/API/index.js:246:14)
at Layer.handle [as handle_request] (/root/API/node_modules/express/lib/router/layer.js:95:5)
我的代码如下:
外部快递服务器:
const allowedIps = [
'194.156.79.100',
'198.244.203.125'
];
/**
* class {Settings}
* params {port} Port + extension number endpoint.
* Whitelist API Endpoint
**/
class Settings {
constructor(port, filePath) {
this.app = express();
this.port = port;
this.ip = '194.156.79.100';
this.filePath = filePath;
this.configureMiddleware();
this.configureRoutes();
this.start();
}
configureMiddleware() {
this.app.use(bodyParser.urlencoded({
extended: true
}));
this.app.use(express.json());
this.app.use(requestIp.mw());
this.app.use(this.requestHandler);
}
requestHandler(req, res, next) {
const remoteIp = req.ip || req.connection.remoteAddress;
const ipv4Regex = /^::ffff:(\d+\.\d+\.\d+\.\d+)$/;
const matches = ipv4Regex.exec(remoteIp);
const actualIp = matches ? matches[1] : remoteIp;
console.log(`Incoming request from IP address: ${actualIp}`);
if (allowedIps.includes(actualIp)) {
return next();
} else {
return res.status(403).send('Access denied');
}
}
configureRoutes() {
this.app.post('/api/settings', this.handleSettingsRequest.bind(this));
}
handleSettingsRequest(req, res, next) {
const {
banMessage,
deviceBlacklist,
gamerscoreRequirement,
realmCode,
whitelistEnabled
} = req.body;
// Convert whitelistEnabled to a Boolean
const whitelistEnabledBool = Boolean(JSON.parse(whitelistEnabled));
// Validate the request data
if (!banMessage || !deviceBlacklist || !gamerscoreRequirement || !realmCode) {
const err = new Error('Invalid request data');
err.status = 400; // Bad Request
next(err);
return;
}
// Do something with the received data
console.log('Received Ban Message:', banMessage);
console.log('Received Device Blacklist:', deviceBlacklist);
console.log('Received Gamerscore Requirement:', gamerscoreRequirement);
console.log('Received Whitelist Enabled:', whitelistEnabledBool);
console.log('Received Realm Code:', realmCode);
const data = JSON.stringify({
banMessage,
deviceBlackList: deviceBlacklist,
gamerscoreRequirement,
whitelistEnabledBool,
realmCode
}, null, 2);
fs.writeFile(this.filePath, data, (err) => {
if (err) {
console.error(err);
return res.status(500).send('Error while writing data to file');
} else {
console.log('Data has been written to the file.');
return res.send('Settings updated successfully');
}
});
}
start() {
this.app.listen(this.port, this.ip, () => {});
}
}
Web 服务器文件:
configAPI.php - 处理请求数据:
<?php
session_start();
// Check if form was submitted
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// Parse incoming JSON data
$data = [
'banMessage' => filter_input(INPUT_POST, 'banMessage', FILTER_SANITIZE_STRING),
'deviceBlacklist' => filter_input(INPUT_POST, 'deviceBlacklist', FILTER_SANITIZE_STRING),
'gamerscoreRequirement' => filter_input(INPUT_POST, 'gamerscoreRequirement', FILTER_SANITIZE_NUMBER_INT),
'whitelistEnabled' => filter_input(INPUT_POST, 'whitelistEnabled', FILTER_VALIDATE_BOOLEAN),
'realmCode' => filter_input(INPUT_POST, 'realmCode', FILTER_SANITIZE_STRING),
];
// Set up cURL request
$url = 'http://194.156.79.100:400' . $_SESSION['id'] . '/api/settings';
$ch = curl_init($url);
$headers = ['Content-Type: application/json'];
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
// Send request and check for errors
$response = curl_exec($ch);
$error = curl_error($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($error) {
http_response_code(500);
exit("cURL Error: " . $error);
} elseif ($httpCode !== 200) {
http_response_code($httpCode);
exit("API Error: " . $response);
} else {
// Redirect the user back to home.php
header("Location: home.php");
exit();
}
}
// If no form was submitted, return an error message
http_response_code(400);
exit("Bad Request");
botConfig.php - 具有表单输入和所有其他 html 位和 bob
<form method="post" action="configAPI.php">
<div class="input-form">
<h2 class="form-title" style="text-align: center;">General Config</h2>
</h2>
<div class="input-container ic1">
<label for="banMessage" class="placeholder"></label>
<input id="banMessage" class="input" type="text" placeholder=" " name="banMessage"/>
<div class="cut">
<p class="cut-text">Ban Message</p>
</div>
</div>
<div class="input-container ic1">
<label for="deviceBlacklist" class="placeholder"></label>
<input id="deviceBlacklist" class="input" type="text" placeholder=" " name="deviceBlacklist"/>
<div class="cut">
<p class="cut-text">Blacklisted Devices</p>
</div>
</div>
<div class="input-container ic1">
<label for="gamerscoreRequirement" class="placeholder"></label>
<input id="gamerscoreRequirement" class="input" type="number" placeholder=" " name="gamerscoreReqirement"/>
<div class="cut">
<p class="cut-text">Gamerscore Requirement</p>
</div>
</div>
<div class="input-container ic1">
<label for="realmCode" class="placeholder"></label>
<input id="realmCode" class="input" type="text" placeholder=" " name="realmCode"/>
<div class="cut">
<p class="cut-text">Realm Code</p>
</div>
</div>
<div class="input-container ic1">
<label class="switch-sm" style="margin-top: 5px;">
<input type="checkbox" class="input" id="whitelistEnabled" placeholder=" " name="whitelistEnabled">
<span class="slider"></span>
</label>
<div class="cut">
<p class="cut-text">Whitelist</p>
</div>
</div>
<input type="submit" class="submit" value="Save">
</div>
</form>
我可能只是个白痴,但是是的,我想不通,我已经尝试了很多。我尝试删除特定项目,例如启用白名单的设置,因为我认为这是最有可能导致问题的