PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, October 20, 2022

[FIXED] How to use fastify-cors to enable just one api to cross domain?

 October 20, 2022     fastify, node.js     No comments   

Issue

I want to let [POST] localhost/product just this API to cross-domain.

I don't know how to do it

fastify.register(require('fastify-cors'), {
  origin:'*',
  methods:['POST'],
  
})

this is my API:

{
      method: 'POST',
      url: '/product',
      handler: productsController.addProduct,
},

Solution

In this case, an external dependency is not required. Instead, set the CORS headers manually in productsController.addProduct.

Example of manual CORS header manipulation:

function addProduct(request, reply) {
  reply.header("Access-Control-Allow-Origin", "*");
  reply.header("Access-Control-Allow-Methods", "POST");
  // ... more code here ...
}

If you still want to use fastify-cors, try something like this:

fastify.register((fastify, options, done) => {
  fastify.register(require("fastify-cors"), {
    origin: "*",
    methods: ["POST"]
  });
  fastify.route({
    method: "POST",
    url: "/product",
    handler: productsController.addProduct
  });
  done();
});


Answered By - luawtf
Answer Checked By - Timothy Miller (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing