问题描述
我想让 [POST] 本地主机/产品 只需这个 API 即可跨域。
我不知道怎么做
if (snapshot.hasData)
return SizedBox(
child: ListView.builder(
// scrollDirection: Axis.horizontal,itemCount: indexLength,controller: PageController(viewportFraction: 1.0),// onPageChanged: (int index) => setState(() => _index = index),itemBuilder: (_,i) {
return SingleChildScrollView(
child: Card(
margin: EdgeInsets.all(10),child: Wrap(
children: <Widget>[
ListTile(
leading: CircleAvatar(
backgroundColor: kPrimaryColor.withOpacity(0.8),backgroundImage: Assetimage('assets/images/nullUser.png'),child: snapshot.data[i]['PhotoURL'] != null
? ClipRRect(
borderRadius: BorderRadius.circular(50),child:
Image.network(snapshot.data[i]['PhotoURL'],width: 50,height: 50,fit: BoxFit.cover,),)
: ClipRRect(
borderRadius: BorderRadius.circular(50),child:
Image.asset('assets/images/nullUser.png',)
),title: Text(
snapshot.data[i]['Email'],style: TextStyle(
fontSize: 16,fontWeight: FontWeight.w700,color: Colors.black.withOpacity(0.7),subtitle: Text(
snapshot.data[i]['Time'],style: TextStyle(
color: Colors.black.withOpacity(0.6)),Padding(
padding: const EdgeInsets.all(16.0),child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,children: [
Container(
decoration: Boxdecoration(
borderRadius:
BorderRadius.all(Radius.circular(5)),color: Colors.grey[200],padding: EdgeInsets.all(10),child: Text(
snapshot.data[i]['Description'],style: TextStyle(
color: Colors.black.withOpacity(0.6)),SizedBox(
height: 8,Container(
decoration: Boxdecoration(
borderRadius:
BorderRadius.all(Radius.circular(5)),border:
Border.all(color: Colors.grey[300])),child: ListTile(
leading: Icon(Icons.category_outlined),title: Text(
'Category : ${snapshot.data[i]['Category']}',style: TextStyle(
fontSize: 14,color: Colors.grey,SizedBox(height: 8),child: ListTile(
leading: Icon(Icons.location_pin),title: Text(
snapshot.data[i]['Location'],child: ListTile(
leading: Icon(
Icons.attach_money,color: kGreenColor,title: Text(
'Budget : Rs.${snapshot.data[i]['Budget']}',child: ListTile(
leading: Icon(Icons.timer),title: Text(
'Duration : ${snapshot.data[i]['Duration']}',SizedBox(
height: 35,sendOfferButton(),SizedBox(
height: 15,Center(
child: Text(
"${i + 1}/$indexLength",style: TextStyle(fontSize: 13),],);
},);
这是我的 API:
fastify.register(require('fastify-cors'),{
origin:'*',methods:['POST'],})
解决方法
在这种情况下,不需要外部依赖。而是在 productsController.addProduct
中手动设置 CORS 标头。
手动 CORS 标头操作示例:
function addProduct(request,reply) {
reply.header("Access-Control-Allow-Origin","*");
reply.header("Access-Control-Allow-Methods","POST");
// ... more code here ...
}
如果您仍想使用 fastify-cors
,请尝试以下操作:
fastify.register((fastify,options,done) => {
fastify.register(require("fastify-cors"),{
origin: "*",methods: ["POST"]
});
fastify.route({
method: "POST",url: "/product",handler: productsController.addProduct
});
done();
});