2017-05-18 43 views
1

我想通過不同的域登錄,而我的服務器是另一個存在。我的loginmodule.js從HTML頁面收集用戶名和密碼是code.i am也允許Cors在代碼中。使用節點js快速登錄後活動拋出401錯誤

var name=$('#username').val(); 
var pass=$('#password').val(); 
var surl = "http://192.165.2.33:3000/users/login/"; 
      console.log('link'); 
    $.ajax({ 
     type: 'POST', 
     url: surl, 
     crossDomain: true, 
     contentType: "application/json; charset=utf-8", 
     data: JSON.stringify({ username:'name', password:'pass'}), 
     dataType: "json", 
     async: true, 
     cache: false, 
     success: function(responseText,status){ 
      if(status=='true') console.log('success'); 

     } 
    }); 

這是給我一個401未經授權的錯誤。我的server.js文件中應包含哪些內容以避免相同。我的Server.js文件有以下代碼。

var allowCrossDomain = function(req, res, next) { 
res.header('Access-Control-Allow-Origin', '*'); 
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS'); 
res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization, Content-Length, X-Requested-With'); 

// intercept OPTIONS method 
if ('OPTIONS' == req.method) { 
    res.send(200); 
} 
else { 
    next(); 
    } 
}; 

的話,我已經把這個頂部

app.use(allowCrossDomain); 
+0

取決於您發佈到 – Brian

+0

的路線上的內容您應該在服務器「crossDomain:true」上允許** CORS **,這不會幫助您執行cors。告訴我們你的'server.js'代碼,我假設你使用** NodeJS **,對吧? – codtex

+0

您好我已經添加了server.js文件供您參考。請檢查 。 – KRISHNA

回答

0

您可以發送此(不是變量,但字符串):

... 
data: JSON.stringify({ username:'name', password:'pass'}), 
... 

但你可能要發送(html輸入的實際內容):

... 
data: JSON.stringify({ username:name, password:pass}), 
... 

因此刪除apotrophes,它應該工作正常!

+0

非常感謝。這工作! – KRISHNA