节点CORS策略:所请求的资源上不存在“ Access-Control-Allow-Origin”标头

时间:2019-11-05 19:07:28

标签: node.js cors localhost

我正在使用端口8080和8082的两个服务器,其中8082在客户端运行,而8080充当中间件。 我正在使用html按钮在服务器到中间件之间进行http标注,但是它给出了错误“ 从起源'http://localhost:8080/'在'http://localhost:8082'处对XMLHttpRequest的访问已被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 :(得分:0)

那不是您使用快递的方式。

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 也是如此。

答案 1 :(得分:0)

只需使用Express,它就可以工作。.替换和发布新文件: 这些文件将具有以下功能:

  1. 创建并启动两个不同的服务器。
  2. 从8082端口的html文件中调用中间件服务器。
  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>