React17 , CRA项目添加Access-Control-Allow-Origin header
Thankfully, there's a solution. I configure the Create React App (CRA) development server to send the Access - Control - Allow - Origin header directly. This simple yet effective configuration is extremely useful if you want to expose your development server as a simple API endpoint for other clients to access without a separate backend server during development.
Here's how you can do it using the src/setupProxy.js file:
-
Create
src/setupProxy.js(if it doesn't exist): In your project'ssrcdirectory, create a file namedsetupProxy.js. -
Add the following code:
- Restart your dev server
\src\setupProxy.js
const { createProxyMiddleware } = require('http-proxy-middleware');
module.exports = function(app) {
app.use(
'/', // Apply to all routes of the dev server
(req, res, next) => {
res.setHeader('Access-Control-Allow-Origin', '*'); // Allow requests from any origin
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS'); // Specify allowed methods
res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization'); // Specify allowed headers
next();
}
);
};

浙公网安备 33010602011771号