XMLHttpRequest cannot load http://localhost:3000/. No ' Access-control-allow-origin ' header is present on the requested resource. Origin ' null ' is therefore not allowed access.
Above is an exception I encountered in my study of Nodejs, with code and solutions below.
1) JS file code
var http=require (' http ');
var querystring=require (' QueryString ');
Http.createserver (function (req,res) {
var postdata= ';
Req.setencoding (' UTF8 ');
Req.on (' Data ', function (chunk) {
Postdata+=chunk;
});
Req.on (' End ', function () {
Res.end (postdata+ "hehe");
});
}). Listen (3000);
Console.log ("Service startup ... ")
2) Front-end HTML page code
<! DOCTYPE html>
<meta charset= "UTF-8" >
<title></title>
<script src= "Jquery-1.8.3.js" ></script>
<script type= "Text/javascript" >
$ (function () {
$ ("#test"). Click (function () {
$.ajax ({
' URL ': ' http://localhost:3000 ',
' method ': ' POST ',
' Data ': {},
' Success ': function (data) {
Console.log (data);
}
});
});
})
</script>
<body>
<p id= "Test" >click me</p>
</body>
This is a simple Ajax access Nodejs Server demo, my service runs on the WINDOWS10 system.
Win key +r enter CMD to bring up the command line tool, enter: Node-v to see if Nodejs and version are installed.
Using the CD command to locate the directory where JS files are located, enter: Node JS file name to run JS files
Google Chrome opens the HTML file by clicking the click Me and then pressing F12 to find the above mentioned error.
Solve the idea, Baidu discovered is the Ajax cross-domain access problem
The first line in the Createserver method is set Res.setheader (' Access-control-allow-origin ', ' * ');
The * symbol allows any request to be made, and of course the actual production environment is unlikely to do so.
You can find the rejected domain by error message and then set Res.setheader (' Access-control-allow-origin ', ' domain name ');
For example, I open the HTML file in the Hbulider is so set Res.setheader (' Access-control-allow-origin ', ' http://localhost:8020 ');
Open the HTML file locally directly so you can set Res.setheader (' Access-control-allow-origin ', ' null ');
can be compared to Java or C # and other service-side languages
Nodejs how easy it is to build a Web service without the need for an HTTP server such as Tomcat because it has a built-in HTTP server.
Nodejs front-end cross-domain access