Node.js向Apache上的login.php发送POST请求出现400错误求助
问题分析与解决方案
你的代码触发Apache返回400 Bad Request,主要是以下几个问题导致的,逐一修复即可:
1. 请求路径格式错误
HTTP请求的path必须是绝对路径(以/开头),你当前的path: 'project/php/login.php'是相对路径格式,Apache无法正确解析,直接返回400错误。
修复:
修改options中的path字段:
const options = { hostname: 'localhost', path: '/project/php/login.php', // 开头添加斜杠 method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded', } };
2. 未启用body-parser中间件
你虽然引入了body-parser,但没有在路由中配置使用,导致req.body.username和req.body.password会是undefined,发送给PHP的参数无效,触发Apache的解析错误。
修复:
在路由代码顶部添加中间件配置:
const express = require('express'); const path = require('path'); const router = express.Router(); const bodyParser = require('body-parser'); const http = require('http'); const querystring = require('querystring'); // 后面编码参数会用到 // 启用body-parser解析表单数据 router.use(bodyParser.urlencoded({ extended: false }));
3. 可选:指定Apache运行端口
你提到Apache运行在80和8080端口,如果实际使用的是8080,http.request默认会请求80端口,可能导致连接异常。
修复:
在options中添加port字段:
const options = { hostname: 'localhost', port: 8080, // 根据你的Apache实际端口修改,80则可以省略 path: '/project/php/login.php', method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded', } };
4. 参数未做URL编码(潜在问题)
直接拼接字符串传递参数,如果用户名/密码包含特殊字符(如&、空格、中文),会破坏请求体格式,导致Apache无法解析。
修复:
使用querystring模块对参数进行编码:
// 替换原有的authReq.write代码 authReq.write(querystring.stringify({ username, password }));
修改后的完整login.js代码
const express = require('express'); const path = require('path'); const router = express.Router(); const bodyParser = require('body-parser'); const http = require('http'); const querystring = require('querystring'); // 启用body-parser解析表单数据 router.use(bodyParser.urlencoded({ extended: false })); const options = { hostname: 'localhost', port: 80, // 改为你的Apache实际端口,比如8080 path: '/project/php/login.php', method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded', } }; /* GET login page. */ router.get('/', function (req, res, next) { res.sendFile(path.join(__dirname, '..', 'views', 'login.html')); }); /* POST login data */ router.post('/', function (req, res, next) { const username = req.body.username; const password = req.body.password; const authReq = http.request(options, (authRes) => { console.log(`Status: ${authRes.statusCode}`); console.log(`Headers: ${JSON.stringify(authRes.headers)}`); authRes.setEncoding('utf8'); let responseBody = ''; authRes.on('data', (chunk) => { responseBody += chunk; console.log(`Body chunk: ${chunk}`); }); authRes.on('end', () => { console.log('No more data in response.'); // 可选:把PHP的响应返回给前端 res.send(responseBody); }); }); authReq.on('error', (e) => { console.error(`Problem with request: ${e.message}`); res.status(500).send('Login verification failed'); }); // 编码并发送参数 authReq.write(querystring.stringify({ username, password })); authReq.end(); }); module.exports = router;
内容的提问来源于stack exchange,提问作者young03600
相关产品推荐
相关产品推荐

