跨域调试bug
跨域调试bug 产品分类:uniCloud/支付宝小程序云
开发环境 | 版本号 | 项目创建方式 |
---|---|---|
示例代码:
<script>
async function fetchDatasetFields() {
const cloudFunctionName = 'cs'; // 可替换为任意云函数名,如 POST_auth
const url = `https://env-*****.dev-hz.cloudbasefunction.cn/${cloudFunctionName}`;
const payload = {
dataset: "users" // 模拟参数,根据需求自定义
};
try {
const response = await fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(payload)
});
const data = await response.json();
document.getElementById('result').textContent = JSON.stringify(data, null, 2);
} catch (error) {
document.getElementById('result').textContent = '请求出错:' + error;
}
}
</script>
操作步骤:
'use strict';
exports.main = async (event, context) => {
// 获取 HTTP 方法
const method = event.httpMethod;
// 获取请求头和参数
const headers = event.headers;
const queryParams = event.queryStringParameters;
const body = event.body;
const isBase64Encoded = event.isBase64Encoded;
// 如果是预检请求,直接返回 CORS 头
if (method === 'OPTIONS') {
return {
statusCode: 204,
headers: {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'GET, POST, OPTIONS',
'Access-Control-Allow-Headers': 'Content-Type'
},
body: ''
};
}
// 正常处理 POST 请求
if (method === 'POST') {
// 如果 body 是 Base64 编码的,需要解码
const parsedBody = isBase64Encoded ? Buffer.from(body, 'base64').toString('utf-8') : body;
return {
statusCode: 200,
headers: {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'GET, POST, OPTIONS',
'Access-Control-Allow-Headers': 'Content-Type'
},
body: JSON.stringify({
msg: '成功',
received: parsedBody // 返回收到的请求体
})
};
}
// 其他类型请求默认返回错误
return {
statusCode: 400,
body: JSON.stringify({ error: 'Unsupported HTTP method' })
};
};
预期结果:
{
"statusCode": 200,
"headers": {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "GET, POST, OPTIONS",
"Access-Control-Allow-Headers": "Content-Type"
},
"body": "{\"msg\":\"成功\",\"received\":\"{\\"dataset\\":\\"users\\"}\"}"
}
实际结果:
Access to fetch at 'https://env-***.dev-hz.cloudbasefunction.cn/cs' from origin 'http://127.0.0.1:8000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
(索引):43
POST https://env-***.dev-hz.cloudbasefunction.cn/cs net::ERR_FAILED
fetchDatasetFields @ (索引):43
onclick @ (索引):29
3 回复
你浏览器上显示的是 127.0.0.1:8080 把? 那就把它也加入跨域白名单
加上了,也不行还是一样的报错,我换成其他端口也加了都不行,就是突然不行的,2周前我用还能没问题
回复 1***@qq.com: 但是你的错误提示确实是跨域,你试试写一个空函数直接return,看访问是否正常还是也是报跨域