2017-07-02 30 views
0

我已閱讀幾乎每篇文章,我都可以在此找到,但他們沒有解決我的問題。快報請求正文/查詢爲空

我:

var cors = require('./cors.js'); 
app.use(bodyParser.json()); 
app.use(bodyParser.urlencoded({ extended: true })); 
  • 我有CORS設置爲允許請求。
  • 我送我的POST請求與'Content-Type': 'application/json'

然而,我的路線的請求對象仍然是空的。

它工作正常,如果我通過參數發送我的數據,但我真的更喜歡使用正文。

請求代碼:

data = { 
    "url": "./text file name.txt", 
    "body": "test content" 
}; 

$.ajax({ 
    'type': 'POST', 
    'Content-Type': 'application/json', 
    'url': 'http://localhost:3000/save', 
    'body': JSON.stringify(data), 
    'success': function(response){ 
     console.log('SUCCESS >>> ', response); 
    }, 
    'error': function(error){ 
     console.log('ERROR >>> ', error.responseText); 
    } 
}); 

路線:

app.post('/save', function(request, response) { 
    console.log('Save Req >> ', request.url, request.body, request.query); 
    // outputs: "Save Req >> /save {} {}" 
}); 

CORS:(cors.js)

module.exports = function() { 
    return function(req, res, next) { 
    res.header("Access-Control-Allow-Origin", "*"); 
    res.header('Access-Control-Allow-Headers', 'Content-Type'); 
    res.header('Access-Control-Allow-Methods', 'PUT, GET, POST, DELETE, OPTIONS'); 
    next(); 
    }; 
} 
+0

標題應該通過'headers'屬性設置,你是否嘗試過(例如'headers:{'Content-Type':'application/json'}')? – mscdex

+0

@mscdex - 當我嘗試時,它將我的請求類型更改爲OPTIONS,儘管將其設置爲POST。然後我得到一個HTTP錯誤。 – Karric

+0

你必須設置你的服務器來處理CORS請求,因爲我相信'localhost'是一個特殊情況(假設你的客戶端腳本通過同一個主機和端口 - localhost:3000'服務)。另外,當提交請求到'localhost'時,並不是所有瀏覽器都可能有相同的行爲。 – mscdex

回答

1

根據身體$就數據在data被傳遞,不在body。像這樣

$.ajax({ 
    type: "POST", 
    url: url, 
    data: data, 
    success: success, 
    dataType: dataType 
}); 
+0

這工作,但它很混亂;爲什麼請求使用'data'作爲關鍵字,然後路由通過'request.body'鍵訪問它? – Karric