CORS错误随机发生

时间:2017-03-28 16:13:51

标签: javascript node.js ajax

所以我正在使用AJAX发送数据来表达,问题是即使每次都发送完全相同的数据,我有两种不同的结果:

  1. 我收到了CORS错误
  2. 流程没有错误,但服务器说数据未定义
  3. 为什么有时会出现CORS错误? 为什么(当CORS没有失败时)服务器是否说数据未定义?

    问题#2的代码:

    客户方:

    document.getElementById('depositButton').onclick = function() {
        var steamid = getSteamID();
        if(steamid == "") {
            alert("Something went horribly wrong, please inform us about this issue by DM'ing us at https://twitter.com/csgobeararms");
        }
    
        console.log(JSON.stringify({arr:items}));
        $.ajax({
            type: 'POST',
            url: 'http://localhost:1337/deposit?steamid=' + steamid,
            data: {arr:items},
            success: function(data) {
                console.log("Tradeoffer has been sent");
            },
            error: function(data) {
                alert("Failed to call bot, please inform us about this issue by DM'ing us at https://twitter.com/csgobeararms (Additional info in console)");
                console.log("Failed to call bot, please inform us about this issue by DM'ing us at https://twitter.com/csgobeararms");
                console.log("This is what we know: ");
                console.log(data);
            }
        });
    }
    
    function getSteamID() {
        var cookie = getCookie("steamid");
        if(cookie != "") {
            return cookie;
        } else {
            return "";
        }
    }
    
    function getCookie(cookie) {
        var name = cookie + "=";
        var decoded = decodeURIComponent(document.cookie);
        var ca = decoded.split(';');
        for(var i = 0; i < ca.length; i++) {
            var c = ca[i];
            while(c.charAt(0) == ' ') {
                c = c.substring(1);
            }
    
            if(c.indexOf(name) == 0) {
                return c.substring(name.length, c.length);
            }
        }
        return "";
    }
    

    服务器端:

    var bodyParser = require('body-parser');
    var express = require('express');
    var app = express();
    app.use(bodyParser.json());
    
    app.use(function(err, req, res, next) {
        console.error(err.stack);
        console.log("ezpzlmnsqz")
        res.status(500).send("Something went horribly wrong!");
    });
    
    app.post('/deposit', function(req, res) {
        console.log('Deposit request recieved, info:');
        console.log('STEAM ID: ' + req.query.steamid);
        console.log('ITEMS: ' + req.params.arr);
        res.status(200).send('Success');
    });
    
    app.listen(1337);
    

0 个答案:

没有答案