【问题标题】:Ajex post JSon report error, how to fix it?Ajax post JSon 报错,如何解决?
【发布时间】:2016-12-18 14:43:43
【问题描述】:

我正在尝试将 JSON 数据发送到服务器并接收。 这是我的服务器 API 代码:

   var express    = require('express');      
   var app        = express();               
   var bodyParser = require('body-parser');

   app.use(bodyParser.urlencoded({ extended: true }));
   app.use(bodyParser.json());

   var port = process.env.PORT || 8080;        
   var router = express.Router();             
   app.use('/api', router); 

   router.post('/', function (req, res) 
   {
     res.json({ message: 'you are doing post ' });   
   })

  app.listen(port);
  console.log('Magic happens on port ' + port);

我用“邮递员”测试过,它反应很好。

当我尝试使用以下代码从客户端获取响应时

function BestTourModel() 
{
    var self = this;
    self.serverURI = 'http://localhost:8080/api';

    self.ajax = function(uri, method, data) 
    {
        var request = {
                        url: uri,
                        type: method,
                        contentType: "application/json",
                        accepts: "application/json",
                        cache: false,
                        dataType: 'json',
                        data: JSON.stringify(data),
                        success: function(data){alert(data);},
                        failure: function(errMsg) { alert(errMsg);}
                       };
        return $.ajax(request);
    }

    self.run_algorithm = function()
    {
        if(self.input_value())
        {               
            var markers = [{ "a": "11", "b": "7" },
                           { "a": "44", "b": "19" },
                           { "a": "45", "b": "-3" }];

            self.ajax(self.serverURI(), 'POST', markers).done(function(data) 
            {
                console.log(data); //this prints received data
            });
        }

    }
}

var bestTourModel = new BestTourModel();
ko.applyBindings(bestTourModel, $('#main')[0]);

“run_algorithm”绑定到一个 html 按钮。

<button class="btn" data-bind="click: $root.run_algorithm" >Run</button>

我试图通过发送显示的 JSon 数据并希望收到一些东西来确认连接,所以我可以发送我的真实数据。但我在 chrom 调试器中遇到错误,如下所示。

XMLHttpRequest cannot load http://localhost:8080/api. Response to preflight 
request doesn't pass access control check: No 'Access-Control-Allow-Origin'
header is present on the requested resource. Origin 'null' is therefore not
allowed access.

请指出我做错了什么。我是新手,请用简单的方式解释一下。

谢谢!

【问题讨论】:

    标签: json rest post


    【解决方案1】:

    在谷歌上搜索并阅读了许多帖子后,找到了解决方案here 最初的想法是given here

    【讨论】:

      猜你喜欢
      • 2019-12-19
      • 2022-01-17
      • 1970-01-01
      • 1970-01-01
      • 2023-01-05
      • 1970-01-01
      • 2013-11-17
      • 2022-12-24
      • 2022-12-29
      相关资源
      最近更新 更多