[POSSIBLY A DUPLICATE]
I have been working on a simple form that will accept the following input element:
<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>
What I want to do is to:
- Pass the input from browser to client-side JavaScript.
- Make an AJAX request
success
to the server-side NODE. - NODE will receive data (user input) and perform some tasks
- NODE will respond back to client-side JavaScript.
- AJAX will receive the respond
complete
and modify some HTML.
JS CODE:
(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 job_country = $("#input02").val();
var job_contract = $("#input03").val();
var job_education = $("#input04").val();
var userInput = JSON.stringify({
job_title,
job_country,
job_contract,
job_education
});
//PASS DATA INTO NODE VIA HTTP POST REQUEST
myAjaxCall("POST", "http://localhost:80/test01", userInput, function(response){
console.log(response);
});
});
});
})();
function myAjaxCall(method, url, userInput, callback) {
$.ajax({
datatype: "jsonp",
contentType: "applicatin/json",
type: method,
url: url,
data: userInput,
success: function (userInput) {
console.log("success");
console.log(userInput);
},
complete: function(responseData) {
console.log("complete");
return callback(responseData);
}
})
}
NODE:
const express = require('express');
const cors = require('cors');
const app = express();
app.use(cors({
origin: '*',
optionsSuccessStatus: 200,
}));
app.post("/test01", (req, res) => {
//get data
//do some stuff
//data to be returned back to client
var object = {
message: "hello world"
}
res.status(200).send(object).end(); //THIS DOESN'T RELOAD PAGE BTW!!!
});
app.listen(80, ()=> {
console.log("\n > Server listening on port: 80");
});
The NODE works okay when accessing http://localhost
from the local machine, but when I try the requests on my website (hosted on noip.com
), that is where it gets tricky. Basically, when I run the above code on my local machine through the public URL that uses my public IP address, it will work fine and return the results I want. I assume this is because the NODE environment is set on my computer locally.
CONSOLE LOG ON LOCAL COMPUTER:
success
parser.js:42 {message: "hello world"}
parser.js:45 complete
parser.js:24 {readyState: 4, getResponseHeader: ƒ, getAllResponseHeaders: ƒ, setRequestHeader: ƒ, overrideMimeType: ƒ, responseJSON: {message: "hello world"}, responseText: "{"message":"hello world"}", ...}
However, when I do this request from another computer also by using the public URL, it will give me an error JSON object back, without the information I want (responseJSON or responseText). I can't figure out why this is happening.
CONSOLE LOG FROM ANOTHER MACHINE:
jquery.min.js:2 Access to XMLHttpRequest at 'http://localhost/test01' from origin 'http://192.168.178.50' 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.
jquery.min.js:2 POST http://localhost/test01 net::ERR_FAILED
parser.js:45 complete
parser.js:24
{readyState: 0, getResponseHeader: ƒ, getAllResponseHeaders: ƒ, setRequestHeader: ƒ, overrideMimeType: ƒ, …}
abort: ƒ (e)
always: ƒ ()
catch: ƒ (e)
done: ƒ ()
fail: ƒ ()
getAllResponseHeaders: ƒ ()
getResponseHeader: ƒ (e)
overrideMimeType: ƒ (e)
pipe: ƒ ()
progress: ƒ ()
promise: ƒ (e)
readyState: 0
setRequestHeader: ƒ (e,t)
state: ƒ ()
status: 0
statusCode: ƒ (e)
statusText: "NetworkError: Failed to execute 'send' on 'XMLHttpRequest': Failed to load 'http://localhost/test01'."
then: ƒ (t,n,r)
_proto_: Object
I have read the following SO posts but couldn't figure out what I did wrong:
- Returning a value from callback function in Node.js
- How do I return the response from an asynchronous call?
UPDATE:
Based on Quentin comment and this link i have modified the code. This will work okay on local computer but not on another computer:
app.use(
cors({
origin: 'http://192.168.178.50',
methods: "GET, POST",
optionsSuccessStatus: 200, // some legacy browsers (IE11, various SmartTVs) choke on 204
preflightContinue: false,
}),
function(req, res, next) {
res.header("Access-Control-Allow-Origin", "http://192.168.178.50"); // update to match the domain you will make the request from
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
}
);