node,express,koa,koa2 cross-domain problem

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.
The above is an exception that I encountered when learning nodejs. There is code and solution below.
1. Noejs Native Solution
1. js file code
var http=require('http');
var querystring=require('querystring');
  var postData='';

console.log("The service starts.")

2. Front-end html page code
<!DOCTYPE html>
<html lang="en">
<meta charset="UTF-8">
<script src="jquery-1.8.3.js"></script>
<script type="text/javascript">
<p id="test">click me</p>

This is a simple ajax access to the nodejs server demo, and my service runs on a windows10 system.

win+R input CMD calls up the command line tool, enter: node-v to see if nodejs and version are installed.

Locate the directory where the js file is located by cd command, enter: node js file name Run js file

Google Browser opens the html file, click me and press F12 to find the error described above.

Solve the problem of ajax cross-domain access by Baidu

Set res.setHeader('Access-Control-Allow-Origin','*') in the first line of the createServer method;

The * number indicates that any and requests are allowed, although this is not possible in the actual production environment.

You can find the rejected domain by error prompt and set res.setHeader('Access-Control-Allow-Origin','Domain Name');

For example, when I open an html file in Sublime Text, I set res.setHeader ('Access-Control-Allow-Origin','http://localhost:8020');

Opening the html file locally directly sets res.setHeader ('Access-Control-Allow-Origin','null');

2. express Solution

Cross-domain issues focus on header s
Start by providing a w3c header definition
Provide a header detailed by a netizen at

These two help you understand the type and role of header s.
Unfortunately, neither of the cross-domain related header attributes found a relevant definition.

Let me tell you directly below

1 is an Access-Control-Allow-Origin allowed domain

2 is the header type allowed by Access-Control-Allow-Headers

The first item can be set directly to * to represent any
But the second one can't be written like this, testing cross-domain discovery errors in chrome.

The final code looks like this:
app.all('*', function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "Content-Type,Content-Length, Authorization, Accept,X-Requested-With");
    res.header("X-Powered-By",' 3.2.1')
    if(req.method=="OPTIONS") res.send(200);/*Quick return of options requests*/
    else  next();

Code Completion:
//allow custom header and CORS
app.all('*',function (req, res, next) {
  res.header('Access-Control-Allow-Origin', '*');
  res.header('Access-Control-Allow-Headers', 'Content-Type, Content-Length, Authorization, Accept, X-Requested-With , yourHeaderFeild');
  res.header('Access-Control-Allow-Methods', 'PUT, POST, GET, DELETE, OPTIONS');

  if (req.method == 'OPTIONS') {
    res.send(200); /Give Way options Request Quick Return/
  else {

Reference: Solve cross-domain access control issues for NodeJS+Express module: Access-Control-Allow-Origin-Tweet

Finally, a cors module is introduced to solve the problem.The code is as follows:

var express = require('express')
  , cors = require('cors')
  , app = express();


app.get('/products/:id', function(req, res, next){
  res.json({msg: 'This is CORS-enabled for all origins!'});

app.listen(80, function(){
  console.log('CORS-enabled web server listening on port 80');

express cors module link expressjs/cors

3. koa Solution
koa also has a cors module. The code is as follows:
var koa = require('koa');
var route = require('koa-route');
var cors = require('koa-cors');
var app = koa();


app.use(route.get('/', function() {
  this.body = { msg: 'Hello World!' };


Keywords: JQuery Javascript Google sublime

Added by jd023 on Tue, 25 Jun 2019 21:14:12 +0300