Политика узла CORS: в запрошенном ресурсе отсутствует заголовок «Access-Control-Allow-Origin» - PullRequest
0 голосов
/ 05 ноября 2019

Я использую два сервера с портами 8080 и 8082, где 8082 работает на стороне клиента, а 8080 действует как промежуточное ПО. Я выполняю обратный вызов http с сервера на промежуточное ПО, используя кнопку html, но выдает ошибку " Доступ к XMLHttpRequest в" http://localhost:8080/' из источника "http://localhost:8082' заблокирован политикой CORS: На запрошенном ресурсе отсутствует заголовок «Access-Control-Allow-Origin»."

Присоединение кода: 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);  

Ответы [ 2 ]

0 голосов
/ 07 ноября 2019

Только что использовал Express и все заработало. Замена и публикация новых файлов: Этот файл будет выполнять следующие функции:

  1. Создать и запустить два разных сервера.
  2. Вызовите промежуточное ПОсервер из файла html с порта 8082.
  3. Извлечение ответа в файле html с сервера промежуточного программного обеспечения.

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>
0 голосов
/ 05 ноября 2019

Вы не используете экспресс.

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

Отправка запроса на получение localhost:8080 вернет Port 8080 started...

То же самое относится к Server.js .

...