首页 > 解决方案 > 节点 Koa cors 不工作

问题描述

使用 koa + 反应server.js

来自 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,尝试从一个REST 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. 为什么?

标签: node.jsreactjskoakoa2

解决方案


这是一种方式。

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

推荐阅读