I have the following form in html on which i pass its data into JavaScript in the following way:
<input type="text" class="form-control" id="input01" name="job_title" placeholder="Enter a job title (e.g. Engineering)">
<button class="btn btn-primary ml-auto" id="form_submit_button">Search</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js "></script>
<script type="text/javascript" src="parser.js"></script>
(function($){
"use strict";
jQuery(document).ready(function($) {
var $this = $(window);
$("#form_submit_button").on("click", function () {
//GET VALUES FROM USER INPUT AND STORE IN VARIABLES
var job_title = $("#input01").val();
var jsonObjects = JSON.stringify({
job_title
});
console.log(jsonObjects);
//PASS DATA INTO NODE VIA HTTP POST REQUEST
const xhr = new XMLHttpRequest();
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.open(
"POST",
"http://localhost:80/test01",
{
job_title,
job_country,
job_contract,
job_education
}
);
xhr.send();
});
});
})();
When I click the button assuming that i have added some data in the input field, the program will pass the information into JavaScript but the http request is not triggered due to the following error:
{"job_title":"database"}
Uncaught DOMException: Failed to execute 'setRequestHeader' on 'XMLHttpRequest': The object's state must be OPENED.
at HTMLButtonElement.<anonymous> (http://public-ip-address/test/parser.js:26:17)
at HTMLButtonElement.dispatch (http://public-ip-address/test/scripts/jquery/jquery.min.js:2:43090)
at HTMLButtonElement.v.handle (http://public-ip-address/test/scripts/jquery/jquery.min.js:2:41074)
When I add the following xhr.setRequestHeader('Content-Type', 'application/json');
below the xhr.open(...)
it will give the following error:
{"job_title":"database"}
Access to XMLHttpRequest at 'http://localhost/test01' from origin 'http://public-ip-address' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Here is the NODE:
const express = require('express');
const app = express();
app.get("/test01", (req, res) => {
res.send("hello world");
})
app.listen(80, ()=> {
console.log("\n > Server running on port: 80");
});
My website is hosted on noip.com using my public ip address. However I cannot and don't know how to access my node server through my URL. Note that http://localhost:80/test01 will show the hello world on the browser.
Any help would be much appreciated, thanks!
UPDATE:
const express = require('express');
const cors = require('cors');
const app = express();
app.use(cors({
origin: '*',
optionsSuccessStatus: 200,
}));
app.get("/test01", (req, res) => {
res.send("hello world");
})
app.listen(80, ()=> {
console.log("\n > Server running on port: 80");
});
ERROR ON BROWSER AFTER UPDATE
POST http://localhost/test01 404 (Not Found)
(anonymous) @ parser.js:39
dispatch @ jquery.min.js:2
v.handle @ jquery.min.js:2