[英]How to run .php script on node.js
我正在使用 wamp 服務器和 node.js 來運行我的應用程序(server.js),但是當我想執行 .php 腳本時,我總是收到一個錯誤: POST http://localhost:8080/login.php 404 (Not Found)
服務器.js
var app = require('express')();
var server = require('http').createServer(app);
var webRTC = require('webrtc.io').listen(server);
var exec = require("child_process").exec;
var port = process.env.PORT || 8080;
server.listen(port);
app.get('/', function(req, res){
res.sendfile(__dirname + '/index.html');
});
app.get('/login.php', function(req, res){
exec("wget -q -O - http://localhost/login.php", function (error, stdout, stderr) {res.send(stdout);});});
在index.html 中調用 login.php:
$("#login").click(function(){
username=$("#user_name").val();
password=$("#password").val();
$.ajax({
type: "POST",
url: "login.php",
data: "name="+username+"&pwd="+password,
success: function(html)
{......
我想問一下,是否需要安裝其他工具或其他東西?
謝謝。
Node.js 不會執行您的 PHP 代碼,Apache 服務器會。 據我了解您的問題,您有一個 Apache 服務器偵聽端口 80,一個 Node.js 服務器偵聽 8080,並且您希望 Node.js 提供的 HTML 頁面在 Apache 提供的 login.php 上執行 Ajax 發布。 如果此斷言為真,那么問題在於您的 Ajax 請求指向 localhost:8080 而不是 localhost:80。
您必須為 Ajax 請求參數提供一個絕對 URL 以正確指向 Apache 服務器(端口 80),現在提供一個相對 URL 將執行對 localhost:8080 的請求,它是您的 Node.js 服務器。
所以,更換:
$.ajax({
type: "POST",
url: "login.php",
data: "name="+username+"&pwd="+password,
經過
$.ajax({
type: "POST",
url: "http://localhost:80/login.php",
data: "name="+username+"&pwd="+password,
應該做的伎倆。
您當然希望從實際頁面獲取服務器地址,您可以在 JavaScript 中這樣做:
$.ajax({
type: "POST",
url: window.location.href.replace(/^(https?:\/\/[^\/]+/,'$1:80/') + "login.php",
data: "name="+username+"&pwd="+password,
要安裝到 Node.js:
npm install node-php
用法
要使用 Node.js 和 Express 運行 WordPress,請執行以下操作:
var express = require('express');
var php = require("php");
var path = require("path");
var app = express();
app.use("/", php.cgi("/path/to/wordpress"));
app.listen(9090);
console.log("Server listening!");
您需要使用與 HTTP 方法相對應的 Express 方法應用程序對象來定義路由。
var express = require('express')
var app = express()
// respond with "hello world" when a GET request is made to the homepage
app.get('/', function (req, res) {
res.send('hello world')
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.