Node Koa cors无法正常工作

时间:2018-05-08 07:23:43

标签: node.js reactjs koa koa2

使用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.");
});

和测试组件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>;
    }
}
方法中的

handleOnClick,尝试从其他API(spring-boot)查询信息,但仍然收到错误:

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

2 个答案:

答案 0 :(得分:2)

根据https://github.com/evert0n/koa-cors/blob/master/examples/custom-options.js中显示的示例,我会尝试在您的server.js代码中添加以下CORS选项,以允许来自所有来源的请求。

var options = {
    origin: '*'
};

app.use(cors(options));

origin选项控制错误消息中提到的Access-Control-Allow-Origin标题。

答案 1 :(得分:0)

这是一种方法。

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