node.js - 节点 Koa cors 不工作
问题描述
使用 koa + 反应server.js
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.
为什么?
解决方案
这是一种方式。
app.use(async (ctx, next) => {
ctx.set('Access-Control-Allow-Origin', '*');
ctx.set('Access-Control-Allow-Methods', 'POST, GET, PUT, DELETE, OPTIONS');
await next();
});
推荐阅读
- gitlab - GitLAB Dedicate Runner 无法联系 pull docker 镜像
- postgresql - 如何使用使用多个数据库的 postgres docker 容器在 init 上为特定数据库运行 *.sql 脚本?
- pandas - 如何将外部数据传递给 Pyomo 约束规则
- javascript - Movie API:如何返回值?
- python - 如何使用 python 连接可从本地计算机中的远程桌面访问的 oracle 数据库?
- python-3.x - TensorFlow ImportError:导入_pywrap_tensorflow_internal时DLL加载失败:找不到指定的模块
- python - 蟒蛇/熊猫;如何保持列的值直到下一个事件
- azure - 在部署 Web 应用程序期间使用 azure devops 提要
- database - Flutter 应用和网站连接到同一个数据库
- javascript - 如何从javascript中的数组中删除某些匹配条件的元素?