gpt4 book ai didi

node.js - Node Koa cors 不工作

转载 作者:太空宇宙 更新时间:2023-11-03 23:00:13 25 4
gpt4 key购买 nike

使用 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中,尝试从rest API(spring-boot)查询信息,但仍然收到错误:


请求的资源上不存在“Access-Control-Allow-Origin” header 。因此,不允许访问源“http://127.0.0.1:3001”。
为什么?

最佳答案

这是一种方法。

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

关于node.js - Node Koa cors 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50228095/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com