简体   繁体   中英

Node CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource

I am using two server of port 8080 and 8082, where 8082 works on client side and 8080 acts as a middleware. I am making a http callout from server to middleware using a html button, but it gives an error " Access to XMLHttpRequest at ' http://localhost:8080/ ' from origin ' http://localhost:8082 ' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. "

Attaching the code: Server.js

var http = require('http');  
var url = require('url');  
var fs = require('fs');  
var cors = require('cors');
var express = require('express');
var app = express();
app.use(cors());
var server = http.createServer(function(request, response,next) {  
    var path = url.parse(request.url).pathname;  
    switch (path) {  
        case '/':  
            response.writeHead(200, {  
                'Content-Type': 'text/plain'  
            });  
            response.write("This is Test Message.");  
            response.end();  
            break;  
        case '/server.html':  
            fs.readFile(__dirname + path, function(error, data) {  
                if (error) {  
                    response.writeHead(404);  
                    response.write(error);  
                    response.end();  
                } else {

                    response.writeHead(200, {  
                        'Content-Type': 'text/html'  
                    });  
                    response.write(data);  
                    response.end();  
                }  
            });  
            break;  
        case '/HtmlPage2.html':  
            fs.readFile(__dirname + path, function(error, data) {  
                if (error) {  
                    response.writeHead(404);  
                    response.write(error);  
                    response.end();  
                } else {  
                    response.writeHead(200, {  
                        'Content-Type': 'text/html'  
                    });  
                    response.write(data);  
                    response.end();  
                }  
            });  
            break;  
        default:  
            response.writeHead(404);  
            response.write("opps this doesn't exist - 404");  
            response.end();  
            break;  
    }  
});  
server.listen(8082); 

Server.html

<!DOCTYPE html>
<html>
  <head>
        <script type="text/javascript" src="server.js"></script>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
        <script>
          function callServer(){
            $.get('http://localhost:8080', function(returnResult) {

            });
            }  
            </script>
    </head>
<body>
        <button onclick="callServer()">Click</button>
</body>

MiddleWareServer.js

var http = require('http');  
var url = require('url');  
var fs = require('fs');  
var cors = require('cors');
var express = require('express');
var app = express();
app.use(cors());

var server = http.createServer(function(request, response,next) {   
    response.writeHead(200, {  
        'Content-Type': 'text/plain'  
    });  
    function returnResult(){
        console.log('Called from the port:8082');
    }
    response.write("Port 8080 started..");  
    response.end();  
});  
server.listen(8080);  

That is not how you use express.

MiddleWareServer.js

var cors = require('cors');
var express = require('express');
var app = express();
app.use(cors());

app.get('/', function(request, response, next) {   
    response.send("Port 8080 started.."); 
})

express.listen(8080);

Sending a get request to localhost:8080 would return Port 8080 started.. .

Same goes for Server.js .

Just used Express and it worked.. Replacing and posting new files: These file will fulfill the following features:

  1. Create and start two different server.
  2. Call the middleware server from a html file from 8082 port.
  3. Fetch the response in html file from middle ware server.

server.js

const express = require('express');
const app = express();
const path = require('path');
const router = express.Router();
var cors = require('cors');
app.use(cors());
router.get('/server',function(req,res){
  res.sendFile(path.join(__dirname+'/server.html'));
});
app.use('/', router);
app.listen(8082);
console.log('Running at Port 8082');

MiddleWareServer.js

const express = require('express');
const app = express();
var cors = require('cors');
app.use(cors());
app.get('/', (req, res) => res.send('Localhost:8080 has been Started'));
app.post('/middlewarehit', function(req,res){
    res.end('Localhost:8080 Hit');
    } 
);
app.listen(8080);
console.log('Running at Port 8080');

server.html

<!DOCTYPE html>
<html>
  <head>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
        <script>
          function callServer(){
            $.ajax({
              url: "http://localhost:8080/middlewarehit",
              type: "POST",
              dataType: '',
              success: function(res){
                $('#response').val(res);
              }
          });
        }  
            </script>
    </head>
<body>
        <input type="text" id="response">
        <button onclick="callServer()">Click</button>
</body>
</html>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM