Javascript 如何将json发布到mocky io

Javascript 如何将json发布到mocky io,javascript,json,url,Javascript,Json,Url,如何使用Javascript将JSON对象发布到Mocky IO URL 我试过: function mocky(req, res) { test = JSON.post( "http://www.mocky.io/v2/5185415ba171ea3a00704eed", { method: "POST" }, function (test, value, ex) { if(

如何使用Javascript将JSON对象发布到Mocky IO URL

我试过:

function mocky(req, res) {
    test = JSON.post(
        "http://www.mocky.io/v2/5185415ba171ea3a00704eed",
        {
            method: "POST"
        },
        function (test, value, ex) {
            if(value){
                console.log(value);
            } else {
                console.log(ex);
            }

        }
    );
}

试试这个典型的jQueryAjax调用-

var jsonData = {"x":"Apple", "y":"Mango"};

$.ajax({
    url: 'http://www.mocky.io/v2/596a5f03110000920701cd92',
    type: 'POST',
    dataType: 'json',
    data: jsonData, 
    success: function() { alert('POST completed'); }
});

在尝试了各种解决方案后,我终于找到了一个效果很好的解决方案

从项目根目录运行以下命令: npm安装请求

//Enabling CORS on ExpressJS
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-    Type, Accept");
next();
});

//Making an API call from NodeJS server
// Posting field (json object) to mocky.io
    var request=require('request');
    var mockyPostRequest = {
        url: 'http://www.mocky.io/v2/596a5f03110000920701cd92',
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        json: field
    };

    request(mockyPostRequest, function(err, res, body) {
        if (res && (res.statusCode === 200 || res.statusCode === 201)) {
            // Logging the post data on the console
            console.log(body);
        }
    });
我使用以下内容作为参考:


感谢大家的回复。

服务器正在抛出错误引用error:$未定义我的index.html:code.jQuery.com/jQuery-1.11.0.min.js中有jQuery“>如果客户端有此代码,则会引发以下错误:XMLHttpRequest无法加载。请求的资源上不存在“Access Control Allow Origin”标头。因此不允许访问源代码“”。请检查现有代码,以查看您正在使用什么,而不是jQuery的
$
。它可能类似于
$j
$jquery
。您在发出跨源请求时会出现此错误,由于安全原因,该请求在默认情况下被阻止。请参考这些链接以进一步深入了解-,我建议删除您的问题。您甚至没有提到您正在使用Node.JS甚至ExpressJS。唯一的另一个答案是某人错误地给了你一个jQuery答案。