1

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
  • 1
    Does this answer your question? [No 'Access-Control-Allow-Origin' - Node / Apache Port Issue](https://stackoverflow.com/questions/18310394/no-access-control-allow-origin-node-apache-port-issue) – Heretic Monkey Aug 05 '20 at 14:03
  • Looks like that the question you have stated does exactly the opposite (access a specific website FROM NODE). Correct me if I'm wrong – user14054150 Aug 05 '20 at 14:19
  • Is the last error from your locally running copy of the website or the one you are accessing through noip? – th1nkful Aug 05 '20 at 14:20
  • All the processes have been accessed via my host name in the noip.com – user14054150 Aug 05 '20 at 14:23
  • ...Which is what your XHR code is doing, and where you get the CORS error from...? – Heretic Monkey Aug 05 '20 at 14:26

1 Answers1

0

You need to configure the CORS headers. You can use the cors npm package to do this easily.

const cors = require('cors');

app.use(cors({
  origin: '*',
  optionsSuccessStatus: 200,
}));

Edit: make sure you add it before your routes

th1nkful
  • 118
  • 1
  • 7
  • Hi, thanks for your reply @th1nkful. It looks like this module will prevent the error but I'm facing a different error now. I have updated my question. I have used your suggestion, reloaded node and browser, added data on input and submitted the button. – user14054150 Aug 05 '20 at 14:01
  • 1
    This question comes in several times a day on Stack Overflow. We don't need more answers. @user14054150 Please see the duplicate question and note the answers there answer the original question. If you have further errors, please do ask a new question, but please search for those errors first, as Stack Overflow was created to answer questions before they even need to be asked. – Heretic Monkey Aug 05 '20 at 14:06
  • As this is a new account, I do not yet have the reputations to vote for an answer. Additionally, the main objective of the question was how to trigger NODE from JavaScript, and yet my question is still unanswered. Should I update my question with more clarification? – user14054150 Aug 05 '20 at 14:15
  • th1nkful, the error can be found at the very end of the question. – user14054150 Aug 05 '20 at 14:17
  • You should ask a new question. – Heretic Monkey Aug 05 '20 at 14:27