Disable OPTIONS request before POST and DELETE requests

Viewed 954

I have a React application based on Typescript which is hosted on my PC. I use Spring gateway to forward requests to another microservice. GET requests are working fine but for POST requests I get:

Access to XMLHttpRequest at 'http://1.1.1.1:8080/api/support/tickets/create' from origin 'http://localhost:3000' 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.

I'm hitting this Spring Cloud Gateway issue: https://github.com/spring-cloud/spring-cloud-gateway/issues/229

React code:

export async function getTicket(id: string) {
  return await axios.get(`${baseUrl}/support/tickets/ticket/${id}`);
}

export async function postTicket(
    data: TicketFullDTO
): Promise<AxiosResponse<TicketFullDTO>> {
  return await axios.post<TicketFullDTO>(
      `${baseUrl}/support/tickets/create`, data);
}

Do you know how I can disable OPTIONS request before POST and DELETE requests?

3 Answers
  • From server, you can return if req.method==="OPTIOINS" inside POST rotues

  • OPTIONS request is automatically sent becase because axios sets custom HTTP headers 'application/json'. With 'application/xml' or 'application/json' headers "OPTIONSare automatically sent. try to set header likeapplication/x-www-form-urlencodedin yourPOSTorDELETE` request

  • Or you can set up proxy from client.

If you are using create-react-app, in src folder create setupProxy.js

 npm install http-proxy-middleware --save

http-proxy-middleware has tons of options

then in setupProxy.js

const { createProxyMiddleware } = require('http-proxy-middleware');


module.exports = function(app) {
  app.use(
    '/api',
    createProxyMiddleware({
      target: 'http://localhost:3080',
      changeOrigin: true,
    })
  );
};

If you are using webpack, https://webpack.js.org/configuration/dev-server/

devServer: {
   historyApiFallBack: true,
   contentBase: path.resolve(__dirname, 'public'),
   proxy: {
      '/v1/**': {
         target: 'http://url',
         secure: false,
         changeOrigin: true
      }
   }
},

If you plan to host the react app and the backend on the same url/port and you only have this issue in development you can set up the local development server to proxy all requests to your backend.

In the package.json file, add:

"proxy": "your-backend-base-url"

You should then execute the backend calls using a relative URL.

Related