0

I have Ubuntu 18.04 running with Apache and NodeJS server. The Apache server is listening on port 80 and 443. A PHP File is executed by the Apache server and is located at: http://server-ip/abc/index.php. It does a Post-Request to the NodeJS sever:

$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

The NodeJS Server (script below) should read the Post-Parameters, do something with it an return a string.

var http = require('http');
http.createServer(function (req, res) {
   //do something
   //return something
}).listen(8080);

When the PHP Script tries to connect to the NodeJS server, i get the CORS same origin error.

2 Answers2

1

Directly you can't start NodeJS serve on specific route location, but you can resolve your problem in two way:

First one is with enabling CORS like below:

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();
});

or use package like cors, for more info visit this link.

The second one is that config Apache to server your Nodejs application behind a proxy like below:

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

More info and same issue for how to serve and config Apache for NodeJS server behind the proxy visit this answer.

0

The port is always defined right after the host. So 127.0.0.1/abc:8080 is nothing else as 127.0.0.1:80/abc:8080 where abc:8080 is handled as a path. You have to bind nodeJs to another port when 8080 is already in use.

tom
  • 9,550
  • 6
  • 30
  • 49