繁体   English   中英

在nodejs中发送http请求到apache服务器上运行的php文件

[英]Send http request in nodejs to php file running on apache server

我要建立自己的实时聊天室,因此我需要使用 nodejs 作为服务器。
在阅读了 socket.io 中的文档后,我决定也使用 express.js。
但在使用 nodejs 之前,我已经在 xampp 上创建了一些 html、php、javascript 文件。
我想使用那些现有的文件,这样我就可以在不重复的情况下进行构建。

在登录部分,我想将数据发布到 login.php 文件以进行验证,因此我使用 http 请求来执行此操作。

apache 在本地主机端口默认端口 (80) 和 8080 上运行
nodejs 在本地主机端口 3000 上运行

路由器中使用了我的 login.js

const express = require('express');
const path = require('path');
const router = express.Router();
const bodyParser = require('body-parser');

const http = require('http');

const options = {
    hostname: 'localhost',
    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');
        authRes.on('data', (chunk) => {
            console.log(`Body: ${chunk}`);
        });
        authRes.on('end', () => {
            console.log('No more data in response.');
        });
    });

    authReq.on('error', (e) => {
        console.error(`Problem with request: ${e.message}`);
    });
    
    // Write the data to be posted to the request body
    authReq.write(`username=${username}&password=${password}`);
    authReq.end();
});

module.exports = router;

但是,我得到了这个回应

POST /login - - ms - -
Status: 400
Headers: {"date":"Mon, 09 Jan 2023 12:48:47 GMT","server":"Apache/2.4.53 (Win64) OpenSSL/1.1.1n PHP/7.4.29","content-length":"334","connection":"close","content-type":"text/html; charset=iso-8859-1"}
Body: <!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html><head>
<title>400 Bad Request</title>
</head><body>
<h1>Bad Request</h1>
<p>Your browser sent a request that this server could not understand.<br />
</p>
<hr>
<address>Apache/2.4.53 (Win64) OpenSSL/1.1.1n PHP/7.4.29 Server at domain Port 80</address>
</body></html>

有什么不对? 任何帮助表示赞赏。

对于像我这样做过傻事的人。

由于选项中的“路径”而出错
路径: 'project/php/login.php'应更改为'/project/php/login.php'

一切正常。

暂无
暂无

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

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