I tried to connect Node with a simple form using AJAX. I have two files.
- The first one is a html file with a textbox and a button.
- The second one is the node server which responds to the request.
My aim is to receive an id from the user (in the textbox) and pass it to the node server (using AJAX call) and the node server returns the id and the corresponding name in JSON format.
Below is my code.
The HTML File with AJAX call
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<input type="text" id="guid" />
<input type="button" id="submit" value="Get" />
</body>
<script>
$('#submit').click(function() {
var id=$('#guid').val();;
$.ajax({
type: 'OPTIONS',
contentType: 'application/JSON; charset=utf-8',
url: 'http://localhost:3300/in/'+id,
success: function(data) {
alert("sucess");
alert(data);
},
error: function() {
alert("failed");
},
});
});
</script>
The error produced is
SyntaxError: JSON.parse: unexpected end of data at line 1 column 1 of the JSON data
The second file is my node server file which is info.js
const expr = require('express');
const app = expr();
app.disable('etag');
app.use(expr.json());
var data=[
{id:"1",name:"aaa"},
{id:"2",name:"bbb"},
{id:"3",name:"ccc"}
];
app.options('/in/:id', function(req, res){
const result = data.find(d=>d.id===req.params.id);
res.set({'Content-Type': 'application/json; charset=utf-8'});
res.send(JSON.stringify(result));
console.log(JSON.stringify(result));
});
app.listen(3300);
console.log("listening to port 3300");
In the above code I changed the method from "GET" to "OPTIONS" as the AJAX call uses OPTIONS as its request type. I have logged the JSON data on the Console and it returns a JSON Format for the requested id.
The screenshots are below. The original web page and in the XHR the error is shown
I tried passing the JSON response to https://jsonlint.com/ and validated it. It shows the response is a proper JSON format. I still can't figure out where i made the mistake. I am a complete beginner to Node so please help me figure out the issue.
The sample input passed is 2. The node responds with the correct name "bbb" and the JSON response {"id":"2","name":"bbb"} is logged on to console. But when passed to the webpage the error is produced.
Edit: I tried running it on Chrome, where the expected response is obtained and the response tab of the XHR shows the JSON data but the error method in the ajax call is executed. But when i tried running it on Firefox this error was produced.