簡體   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