以下代码:
const FCClient = require('@alicloud/fc');
const serviceName = 'tst';
const funcName = 'gettoken';
const client = new FCClient('???', {
accessKeyID: '???',
accessKeySecret: '???',
region: 'cn-shanghai',
timeout: 10000 // Request timeout in milliseconds, default is 10s
});
client.invokeFunction(serviceName, funcName, 'event').then(function(resp) {
console.log('invokeFunction: %j', resp);
console.log(`${JSON.stringify(resp)}`);
}).catch(function(err) {
console.error(err);
});
经本人测试,可以在node环境中执行,但我需要在浏览器端执行;
既然函数计算是serverless架构,肯定希望能在浏览器中直接调用。
结果返回如下错误:
1226487980969891.fc.cn-shanghai.aliyuncs.com/2016-08-15/services/tst/functions/gettoken/invocations Failed to load resource: the server responded with a status of 400 (Bad Request)
09:39:40.947 1226487980969891.fc.cn-shanghai.aliyuncs.com/2016-08-15/services/tst/functions/gettoken/invocations Failed to load resource: the server responded with a status of 400 (Bad Request)
09:39:40.947 localhost/:1 Failed to load 1226487980969891.fc.cn-shanghai.aliyuncs.com/2016-08-15/services/tst/functions/gettoken/invocations: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access. The response had HTTP status code 400. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
09:39:40.948 proxyConsole.js:54 TypeError: Failed to fetch POST 1226487980969891.fc.cn-shanghai.aliyuncs.com/2016-08-15/services/tst/functions/gettoken/invocations failed.
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。
在浏览器端直接调用阿里云函数计算(Function Compute)服务会遇到跨域资源共享(CORS,Cross-Origin Resource Sharing)的问题。从你的错误信息来看,主要问题是由于服务器没有在响应中包含Access-Control-Allow-Origin头,导致浏览器出于安全原因阻止了这次请求。
要解决这个问题,你需要在你的函数计算服务端进行配置,以允许来自特定源或所有源的跨域请求。以下是几种解决方案:
对于阿里云函数计算,你可以在函数的处理逻辑中添加 CORS 相关的 HTTP 头。以下是一个 Node.js 函数示例,展示了如何在返回对象中添加 CORS 头:
exports.handler = async (event, context) => {
const response = {
statusCode: 200,
headers: {
"Content-Type": "application/json",
"Access-Control-Allow-Origin": "*", // 允许所有源访问,也可以指定具体的源,如 "http://localhost:3000"
"Access-Control-Allow-Methods": "GET, POST, PUT, DELETE, HEAD",
"Access-Control-Allow-Headers": "Content-Type, Authorization"
},
body: JSON.stringify({ message: 'Hello from Function Compute!' }),
};
return response;
};
确保你的函数正确处理 OPTIONS 请求,因为浏览器在发送实际的跨域 POST 请求之前,会先发送一个预检(preflight)OPTIONS 请求来检查服务器是否支持跨域访问。
另一种更推荐的方式是将函数计算与阿里云 API 网关结合使用。API 网关天然支持 CORS 配置,并且可以提供更高级的安全控制、流量管理等功能。你只需在创建或编辑 API 网关时,在“CORS”设置中启用 CORS 并配置相应的源即可。
"Access-Control-Allow-Origin": "*" 虽然方便,但存在安全隐患,因为它允许任何网站调用你的接口。在生产环境中,应明确指定允许的源。通过上述方法之一配置后,你应该能够在浏览器环境中成功调用函数计算服务了。