向Wix后端.jsw文件发送GET请求返回404文件未找到问题
确认文件名与路由匹配
Wix后端函数的路由规则是_functions/[文件名],导出函数必须遵循get_[文件名]的命名格式。你的导出函数是get_myAPI,对应的.jsw文件名必须是myAPI.jsw,大小写要完全一致——Wix对文件名大小写敏感,别写成MyApi.jsw或者api.jsw,否则路由不匹配就会返回404。必须发布站点
开发模式下创建的后端函数,只有发布站点后才能通过公网URL访问。别只在编辑器预览里测试,点击右上角「发布」按钮,等发布完成后再用Postman请求。核对域名和路径
确保请求URL用的是站点的正式发布域名,别用编辑器里的预览域名(比如xxx.wixsite.com/xxx这种测试域名要换成你自己的www.mywebsite.com)。另外检查路径是否正确,_functions必须紧跟在根域名后面,如果站点有子路径,要把路径补全,比如https://www.mywebsite.com/blog/_functions/myAPI。检查函数语法和部署状态
打开Wix编辑器的代码控制台,看看有没有语法错误——如果代码有问题,函数会部署失败,自然返回404。还要确认wix-http-functions和wix-data的导入没有报错,导入错误也会导致函数无法正常运行。测试阶段临时放宽CORS配置
用Postman测试时,可以先把Access-Control-Allow-Origin改成*,避免CORS配置干扰测试(虽然404是路径问题,但有时候CORS错误会被混淆),等请求正常后再改回指定域名。
修正转义后的后端函数代码
import {ok, created, notFound, serverError} from 'wix-http-functions'; import wixData from 'wix-data'; export async function get_myAPI(request) { const options = { "suppressAuth": true, "suppressHooks": true }; try { const results = await wixData.query("Registrations").find(options); const data = results.items.map(item => { return { firstName: item.firstName, lastName: item.lastName, phone: item.phone, email: item.email, streetAddress: item.streetAddress, city: item.city, regionStateProvince: item.regionStateProvince, country: item.country, postalZipCode: item.postalZipCode, longAnswerField: item.paragraphField, shortAnswerField: item.shortAnswerField }; }); const response = ok({ body: { data } }); response.headers = { "Content-Type": "application/json", "Access-Control-Allow-Origin": "https://my-website.io", "Access-Control-Allow-Headers": "Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With", "Access-Control-Allow-Methods": "GET, POST, OPTIONS" }; return response; } catch (error) { console.error(error); const response = serverError({ body: { error: error.message } }); response.headers = { "Content-Type": "application/json", "Access-Control-Allow-Origin": "https://my-website.io", "Access-Control-Allow-Headers": "Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With", "Access-Control-Allow-Methods": "GET, POST, OPTIONS" }; return response; } }
内容的提问来源于stack exchange,提问作者lachnroll

