2017-08-10 58 views
1

我有一個AngularFullStack項目,我嘗試使用下面的代碼打我的項目的服務器端點,但問題是呼叫是不是從角度客戶端到nodejs服務器。因爲這是我的第一個項目,所以我很少不知道可能會導致這個奇怪衝突的問題。客戶端無法擊中其自己的服務器端點

客戶方:

$http({ 
     method: 'POST', 
     url: '/api/soapAPIs/soapAPI', 
     data: request, 
     headers: { 
      'Content-Type': 'application/json' 
     } 
     }) 
     .then(function(response) { 
     console.log("response from server is: ", response); 
     }) 
     .catch(function(error) { 
     console.log("error in calling server is: ", error); 
     }); 

我已經安裝在服務器端CORS並寫在app.js下面的代碼,但仍然不起作用。

服務器App.js

// Setup server 
var app = express(); 
var cors = require('cors'); 
//add cors to do the cross site requests 
app.use(cors()); 

服務器端點代碼:

export function soapAPI(req, res) { 
    console.log("SERVER SIDE ", req.body); 
    res.status(statusCode).json({"status":"success"}); 
    res.send(); 
} 

以下是問題:

  1. 如果我嘗試打端點的NodeJS像這/api/soapAPIs/soapAPI,瀏覽器顯示pending請求,它永遠不會去服務器。

  2. 當我爲端點添加完整分類網址(如http:localhost:9000/api/soapAPIs/soapAPI)時,它會擊中端點,但客戶端永遠不會收到來自服務器的響應。我不想在客戶端提供完整的分類網址,原因很明顯。

如何解決此問題?如果您需要其他代碼/信息,請告訴我。

編輯:

用完全分類路徑,服務器端點被擊中,但它的響應永遠不會被客戶端接收。我得到了瀏覽器這個錯誤:

Possibly unhandled rejection: {"data":null,"status":-1,"config":{"method":"GET","transformRequest":[null],"transformResponse":[null],"jsonpCallbackParam":"callback","url":"/api/things","headers":{"Accept":"application/json, text/plain, */*"}},"statusText":""} 
+0

請分享server.js的完整代碼(GIST,github上,..) –

+0

@BadisMerabet你去那裏:https://gist.github.com/wingoku/38a77a2086441a8a752e77373694a938 –

回答

1

取消對以下行:

/*mongoose.connect(config.mongo.uri, config.mongo.options); 
    mongoose.connection.on('error', function(err) { 
    console.error(`MongoDB connection error: ${err}`); 
    process.exit(-1); // eslint-disable-line no-process-exit 
}); 
*/ 

基本上,這是造成你的控制器不返回任何響應,因爲您的貓鼬模型正在被引用,但與mongo的連接失敗。

+0

謝謝這個修復它:) –

+0

非常歡迎 – aliirz

0

你必須發送請求回用res.send()

app.post('/api/soapAPIs/soapAPI',function(req,res){ 
    console.log("SERVER SIDE ", req.body); 
    res.status(statusCode).json({"status":"success"}}); 

    res.send(); 

}) 
+0

我嘗試過了,它仍然沒有工作 –

+0

。 json()方法也發送一個響應。你不必使用.send()/ http://expressjs.com/en/4x/api.html#res.json –

+0

@BadisMerabet我已經嘗試過,沒有res.send(),它仍然沒有沒有工作 –