3

use koa + react server.js

guide from npm koa

const Koa = require("koa");
const KoaRouter = require("koa-router");
const static = require("koa-static");
const cors = require('koa2-cors');
const fs = require("fs");
const path = require("path");
const Promise = require("bluebird");
const cheerio = require("cheerio");
const readFileAsync = Promise.promisify(fs.readFile);

// koa & koa router 
var app = new Koa();
var router = new KoaRouter();

app.use(cors());

async function loadHtml(path) {
    try {
        let content = await readFileAsync(path);
        return cheerio.load(content);
    } catch (e) {
        return false;
    }
}

router.get("/", async (ctx, next) => {
    console.log("index page");
    const $html = await loadHtml(path.resolve(__dirname, "/index.html"));
    if (!$html) {
        ctx.body = "Interal Server Error...";
    }else {
        // console.log($html);
        ctx.body = $html.html();
    }
});

app.use(static(path.join(__dirname, "./dist")))

app.use(router.routes()).use(router.allowedMethods());

app.listen(3001, () => {
    console.log("server start at 3001.");
});

and a test Component UserList

class UserList extends React.Component {
    constructor() {
        super();
        this.state = {}
    }

    handleOnClick() {
        // let div = $("#user-list-div");
        let url = "http://localhost:9001/koa/users";
        $.get(url, function(data, status){
            alert("data: " + data + "\nstatus: " + status);
        });
    }

    render() {
        return <div id="user-list-div" onClick={this.handleOnClick}> user list div. </div>;
    }
}

in the method: handleOnClick, try to query info from a rest API (spring-boot), but still got the error:

No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://127.0.0.1:3001' is therefore not allowed access. why?

Jarvis
  • 371
  • 1
  • 10
  • 22

2 Answers2

4

this is one way.

app.use(async (ctx, next) => {
    ctx.set('Access-Control-Allow-Origin', '*');
    ctx.set('Access-Control-Allow-Methods', 'POST, GET, PUT, DELETE, OPTIONS');
    await next();
});
이재진
  • 71
  • 3
3

Based on the example shown at https://github.com/evert0n/koa-cors/blob/master/examples/custom-options.js, I would try adding the following CORS option in your server.js code to allow requests coming from all origins.

var options = {
    origin: '*'
};

app.use(cors(options));

The origin option controls the Access-Control-Allow-Origin header, which is mentioned in your error message.

M. F.
  • 1,654
  • 11
  • 16