开发者社区 问答 正文

关于函数计算在浏览器端使用的问题

以下代码:

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.

展开
收起
downup2u 2017-09-28 09:44:40 2187 分享 版权
阿里云 AI 助理回答

在浏览器端直接调用阿里云函数计算(Function Compute)服务会遇到跨域资源共享(CORS,Cross-Origin Resource Sharing)的问题。从你的错误信息来看,主要问题是由于服务器没有在响应中包含Access-Control-Allow-Origin头,导致浏览器出于安全原因阻止了这次请求。

要解决这个问题,你需要在你的函数计算服务端进行配置,以允许来自特定源或所有源的跨域请求。以下是几种解决方案:

1. 在函数计算中设置 CORS

对于阿里云函数计算,你可以在函数的处理逻辑中添加 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 请求来检查服务器是否支持跨域访问。

2. 使用 API 网关作为前端

另一种更推荐的方式是将函数计算与阿里云 API 网关结合使用。API 网关天然支持 CORS 配置,并且可以提供更高级的安全控制、流量管理等功能。你只需在创建或编辑 API 网关时,在“CORS”设置中启用 CORS 并配置相应的源即可。

注意事项

  • 安全性:设置 "Access-Control-Allow-Origin": "*" 虽然方便,但存在安全隐患,因为它允许任何网站调用你的接口。在生产环境中,应明确指定允许的源。
  • API 网关:如果选择使用 API 网关,记得在发布 API 后更新客户端代码中的调用 URL。

通过上述方法之一配置后,你应该能够在浏览器环境中成功调用函数计算服务了。

有帮助
无帮助
AI 助理回答生成答案可能存在不准确,仅供参考
0 条回答
写回答
取消 提交回答