Node.js 让NodeJS收听127.0.0.1/abc:8080
我用Apache和NodeJS服务器运行Ubuntu18.04。Apache服务器正在侦听端口80和443。PHP文件由Apache服务器执行,位于:。它向NodeJS服务器发出Post请求:Node.js 让NodeJS收听127.0.0.1/abc:8080,node.js,Node.js,我用Apache和NodeJS服务器运行Ubuntu18.04。Apache服务器正在侦听端口80和443。PHP文件由Apache服务器执行,位于:。它向NodeJS服务器发出Post请求: $postdata = http_build_query( array( 'var1' => 'some content', 'var2' => 'doh' ) ); $opts = array('http' => array(
$postdata = http_build_query(
array(
'var1' => 'some content',
'var2' => 'doh'
)
);
$opts = array('http' =>
array(
'method' => 'POST',
'header' => 'Content-Type: application/x-www-form-urlencoded',
'content' => $postdata
)
);
$context = stream_context_create($opts);
$result = file_get_contents('http://127.0.0.1:8080/', false, $context);
//do something with $result
NodeJS服务器(下面的脚本)应该读取Post参数,使用它做一些事情,并返回一个字符串
var http = require('http');
http.createServer(function (req, res) {
//do something
//return something
}).listen(8080);
当PHP脚本尝试连接到NodeJS服务器时,我得到了CORS同源错误。端口总是在主机之后定义。因此,
127.0.0.1/abc:8080
与127.0.0.1:80/abc:8080
不同,其中abc:8080
作为路径处理。当8080已经在使用时,您必须将NodeJ绑定到另一个端口。您不能直接启动特定路由位置的NodeJ,但您可以通过两种方式解决问题:
第一个是启用CORS,如下所示:
const express = require('express');
const app = express();
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
<VirtualHost *:80>
ServerName example.com
ServerAlias www.example.com
ProxyPreserveHost On
ProxyPass /node http://example.com:3000/node
ProxyPassReverse /node http://example.com:3000/node
</VirtualHost>
或者使用软件包,如需更多信息,请访问此
第二个是配置Apache,以便在代理之后为Nodejs应用程序提供服务器,如下所示:
const express = require('express');
const app = express();
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
<VirtualHost *:80>
ServerName example.com
ServerAlias www.example.com
ProxyPreserveHost On
ProxyPass /node http://example.com:3000/node
ProxyPassReverse /node http://example.com:3000/node
</VirtualHost>
ServerName example.com
ServerAlias www.example.com
代理主机
代理过程/节点http://example.com:3000/node
ProxyPassReverse/节点http://example.com:3000/node
有关如何为NodeJS代理服务器提供服务和配置Apache的更多信息和相同问题,请访问此。无法执行127.0.0.1/abc:8080。我认为如果您的apache运行在8080上,您应该使用另一个端口,如8000或其他端口。请提供您试图实现的详细信息。这有帮助吗@克:我重写了我的问题。真的不明白这个问题。我会尝试第二种方法。