如何在node.js上运行.php脚本
我正在使用wamp server和node.js来运行我的应用程序(server.js),但是当我想要执行.php脚本时,我总是遇到一个错误:如何在node.js上运行.php脚本,php,node.js,Php,Node.js,我正在使用wamp server和node.js来运行我的应用程序(server.js),但是当我想要执行.php脚本时,我总是遇到一个错误: POSThttp://localhost:8080/login.php 404(未找到) server.js var app = require('express')(); var server = require('http').createServer(app); var webRTC = require('webrtc.io').listen(se
POSThttp://localhost:8080/login.php 404(未找到)
server.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 post。如果此断言为真,那么问题在于Ajax请求指向localhost:8080,而不是localhost:80 您必须为Ajax请求参数提供一个绝对URL以正确指向Apache服务器(端口80),现在提供一个相对URL将执行对localhost:8080的请求,localhost:8080是您的Node.js服务器 因此,取代:
$.ajax({
type: "POST",
url: "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 methods app对象定义路由
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')
})
你试过用app.post代替get吗?您的表单正在发送http post。我尝试测试此代码:
http://tutsforweb.blogspot.sk/search/label/ajax
实际上,现在我遇到了一个错误:XMLHttpRequest无法加载http://localhost/login.php. 起源http://localhost:8080 Access Control Allow Origin不允许使用。
您现在必须检查访问控制策略头您的apache web服务器必须返回正确的头才能允许跨域请求
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')
})