react-typescript-web-extension-starter icon indicating copy to clipboard operation
react-typescript-web-extension-starter copied to clipboard

how to resolve CORS block in storybook ?

Open shen-yu opened this issue 5 years ago • 3 comments
trafficstars

hello, i'm configure this to aviod CORS block, but it's not work, how can i do? image

image

shen-yu avatar Mar 11 '20 05:03 shen-yu

I'm trying http-proxy-middleware package, but it's still not work. Can you help me ? Thanks. image

shen-yu avatar Mar 11 '20 05:03 shen-yu

@Shen-Yu Thanks for opening the ticket!

Looks like this can be solved by creating a custom Express.js application that serves Storybook as middleware - there's a helpful GitHub issue here documenting that process.

Looks like you can do something like this to proxy requests through your Express.js app:

var Express = require('express')
var proxy = require('http-proxy-middleware')
var storybook = require('@kadira/storybook/dist/server/middleware').default
var app = new Express()
var port = 4001
var storybookConfig = './.storybook'

app.use(storybook(storybookConfig))

app.use('/api', proxy({
  target: 'https://api-endpoint', // target host
  changeOrigin: true,
}))

app.listen(port, function (error) {
  if (error) {
    console.error(error)
  } else {
    console.info('==>  Listening on port %s. Open up http://localhost:%s/ in your browser.', port, port)
  }
})

I haven't tested this solution myself, but let's leave this ticket open - if anybody else would like to see this available as a core feature in the react-typescript-web-extension-starter please give this comment a :+1:

aeksco avatar Mar 12 '20 22:03 aeksco

I've found a good solution for this inside Storybook:

  • Add "http-proxy-middleware": "^1.0.4", dependency
  • Add .storybook/middleware.js:
const { createProxyMiddleware } = require("http-proxy-middleware");

// Adds Storybook server middleware to proxy requests to /api to http://localhost:3030
// The `http://localhost:3030` target is where local plugins are served when using @codotype/cli
module.exports = function expressMiddleware(router) {
    router.use(
        "/api",
        createProxyMiddleware({
            target: "http://localhost:3030",
            changeOrigin: true,
        }),
    );
};

If anyone wants to add this to the documentation in README.md it would be greatly appreciated!

aeksco avatar Apr 15 '21 07:04 aeksco