【问题标题】:Response to preflight request doesn't pass access control check with AngularJS对预检请求的响应未通过 AngularJS 的访问控制检查
【发布时间】:2016-08-31 09:02:52
【问题描述】:

我该如何解决这个问题? 当我向服务器发送 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));
            }

        }

//我的控制器.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 参数 'data' 时才会出现

【问题讨论】:

    标签: angularjs node.js mobile


    【解决方案1】:

    我认为问题可能在于数据是 JavaScript 对象而不是有效的 JSON

    在 setNewSearch() 函数中试试这个

        $http.post('http://localhost:3000/data-search', JSON.stringify(data)).then(successCallback, errorCallback);
    

    【讨论】:

      【解决方案2】:

      也许您的处理程序抛出错误或处理数据的其他问题阻止它使用允许来源标头进行回复?

      【讨论】:

        猜你喜欢
        • 2018-04-14
        • 2016-06-05
        • 2017-03-25
        • 2019-09-09
        相关资源
        最近更新 更多