我该如何解决这个问题? 当我向服务器发送POST请求时......
XMLHttpRequest cannot load http://localhost:3000/data-search. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8100' is therefore not allowed access.
// myservice.js
function setNewSearch(titleParam, ratingParam) {
var data = {
title: titleParam,
rating: ratingParam
};
$http.post('http://localhost:3000/data-search', data).then(successCallback, errorCallback);
function successCallback(e){
console.log('successCallback ' + JSON.stringify(e));
}
function errorCallback(e){
console.log('errorCallback ' +JSON.stringify(e));
}
}
// my controller.js
$scope.newSearch = function(){
NewSearchService.setNewSearch('john', 'white');
};
//我的服务器是:
app.post('/data-search', insertDataSearch);
function insertDataSearch(req, res) {
// Website you wish to allow to connect
res.setHeader('Access-Control-Allow-Origin', '*');
// Request methods you wish to allow
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
// Request headers you wish to allow
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
// Set to true if you need the website to include cookies in the requests sent
// to the API (e.g. in case you use sessions)
res.setHeader('Access-Control-Allow-Credentials', true);
var newDataSearch = new dataSearch();
newDataSearch.title = req.param('title');
newDataSearch.rating = req.param('rating');
newDataSearch.save(function(err) {
if (err) {
console.log('Error in Saving newDataSearch: ' + err);
throw err;
}
res.send("Sucess");
});
}
当我在$ http.post上输入参数'数据'
时,才会出现此问题答案 0 :(得分:-1)
我认为问题可能是数据是JavaScript对象而不是有效的JSON
在setNewSearch()函数中尝试这个
$http.post('http://localhost:3000/data-search', JSON.stringify(data)).then(successCallback, errorCallback);
答案 1 :(得分:-1)
也许您的处理程序抛出错误或处理数据的其他问题阻止它使用allow origin标头进行回复?