我有一个在开发模式下本地运行的天蓝色函数。我正在尝试导入
node-fetch
:
import { fetch } from "node-fetch";
module.exports = async function (context, req) {
context.log("JavaScript HTTP trigger function processed a request.");
const res = await fetch("https://www.swyx.io/api/rss.xml");
const responseMessage = "res:" + res.ok;
context.res = {
// status: 200, /* Defaults to 200 */
body: responseMessage,
};
};
我收到以下错误:
Worker was unable to load function HttpTrigger1: 'Cannot use import statement outside a module'
我尝试过的:
type: 'module'
添加到 package.json。index.cjs
但它仍然抛出同样的错误。
供参考,这是我的package.json:
{
"name": "cors-test",
"version": "1.0.0",
"description": "",
"type": "module",
"scripts": {
"start": "func start",
"test": "echo \"No tests yet...\""
},
"dependencies": {
"node-fetch": "^3.3.0"
},
"devDependencies": {}
}
这是文件结构:
.
├── host.json
├── HttpTrigger1
│ ├── function.json
│ ├── index.cjs
│ └── sample.dat
├── local.settings.json
├── package.json
├── package-lock.json
└── yarn.lock
我找到了解决方案
module.exports
并使用 export default
代替:import fetch from "node-fetch";
export default async function (context, req) {
context.log("JavaScript HTTP trigger function processed a request.");
const res = await fetch("https://www.swyx.io/api/rss.xml");
const responseMessage = "res:" + res.ok;
context.res = {
// status: 200, /* Defaults to 200 */
body: responseMessage,
};
}
Copilot 的另一个解决方案。无需更改文件名和导入格式:
const { app } = require('@azure/functions');
// const fetch = require('node-fetch'); // this does not work...
app.http('example', {
methods: ['GET'],
authLevel: 'anonymous',
handler: async (request, context) => {
context.log(`Request for "${request.url}"`);
const { default: fetch } = await import('node-fetch'); // this works!
const response = await fetch('https://example.com');
context.log(`Response from example: ${response.status}`);
return {
body: await response.text()
}
}
});