我正在尝试将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);
我用" postman"进行了测试。它反应很好。
当我尝试使用以下代码从客户端获取响应时
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.
请指出我做错了什么。我是新手,请以简单的方式解释。
谢谢!