Question

I need to write simple web service. It will consume Json and if this Json is invalid it needs to return 400 with { "doh":"some error message here"}.

I can send valid Json just fine but for testing I need to send invalid Json and thats what I'm having trouble with. I keep getting:

XMLHttpRequest cannot load http://localhost:3800/. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost' is therefore not allowed access. 

and nothing gets to server. How can I test this service?

Ok, on front end I have this jQuery call:

$.ajax({
    type: "POST",
     url: "http://localhost:3800",

    // this works fine so if json is valid it sends no problem
    // data: JSON.stringify({"baa":"bbb"}),

    // this however with invalid json here below doesn't work and gives me cross origin message: XMLHttpRequest cannot load http://localhost:3800/. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost' is therefore not allowed access. 
    data: JSON.stringify('{aa:a:"bbb"}'),

    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function(data){ console.log(data);},
    failure: function(errMsg) {
        console.log(errMsg);
    }
});

then on server side I have the service itself in NodeJS:

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

app.use(bodyParser());

app.all('/', function(req, res, next) {
    // set origin policy etc so cross-domain access wont be an issue

    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");

    next();
});

app.post('/', function(req, res) {

    // here I will do testing if json passed is valid BUT it doesn't even get here


    if (JSON.parse(JSON.stringify(req.body)))
        res.json('all good');
    else
        res.json({
            success: false,
            error: "json invalid"
        }, 400);


});

app.listen(3800);

How can I send invalid jSon so it can be tested on the server side?

No correct solution

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top