最近在测试一个api,可以用curl命令直接访问,指定header相关配置,request body(JSON),成功后返回一个JSON。
原本想搞个静态页面html,在script标签里用fetch做个简单的demo的,结果就遇到跨域问题。遂使用后端请求,就想到了Nodejs。
既然有现成的工具,那就使用呗。
环境node --version: 18.15.0
1.全局安装express-generator:
npm i express-generator -g
2.生成一个测试项目:
express nodepost
3. 安装依赖
cd nodepost
npm install
4.试运行(没有意外的话可以在浏览器输入 localhost:3000,看到Express 欢迎页)
npm start
5. VSCODE编辑
code .
6.修改routers/index.js, 增加以下代码段,注意按你实际配置来(url, requestData, authkey...)
router.get('/json', (req, res, next) => {
let success = true;
const data = {
k: 'your real data'
};
fetch('https://example.com/api/g', {
method: 'POST',
body: JSON.stringify(data),
headers: {
'Content-type': 'application/json; charset=UTF-8',
'Authorization': 'your real auth key if neccessory, otherwise you could not config this item',
},
}
).then((res) => res.json())
.then((json) => console.log(json))
.catch(err => {
success = false;
console.log('err:', err);
})
res.json({
success
})
});
7.访问 localhost:3000/json, 不出问题的话能在后端控制台查看请求结果
PLUS:
选择新版本的Node,不能低于17.5.0,否则不能直接使用fecth,这blog面有说明。
低版本用node-fetch库或者原生的http模块, node-fetch我自己导入一直有问题,原生http模块要写不少东西,故不采用。