惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

雷峰网
雷峰网
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
T
Tailwind CSS Blog
F
Fortinet All Blogs
Microsoft Azure Blog
Microsoft Azure Blog
Jina AI
Jina AI
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
N
Netflix TechBlog - Medium
B
Blog RSS Feed
Blog — PlanetScale
Blog — PlanetScale
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
T
The Blog of Author Tim Ferriss
D
Docker
博客园 - 聂微东
博客园 - 【当耐特】
博客园 - 三生石上(FineUI控件)
L
LangChain Blog
量子位
宝玉的分享
宝玉的分享
博客园 - 司徒正美
The Cloudflare Blog
G
Google Developers Blog
Microsoft Security Blog
Microsoft Security Blog
腾讯CDC

Nx Blog

Sharing Tailwind CSS Styles Across Apps in a Monorepo | Nx Blog How SiriusXM Stays Competitive by Iterating and Getting to Market Fast | Nx Blog Agentic Experience Is the New Developer Experience | Nx Blog Nx Joins the Linux Foundation and the Agentic AI Foundation | Nx Blog A Monorepo Is NOT a Monolith | Nx Blog Why we deleted (most of) our MCP tools | Nx Blog Teach Your AI Agent How to Work in a Monorepo | Nx Blog How Broadcom stays efficient and nimble with monorepos | Nx Blog Why Monorepos are King in the Age of AI | Nx Blog Nx 2026 Roadmap: Expanding Agent Autonomy, Improving Performance, Better Polyglot and More | Nx Blog End to End Autonomous AI Agent Workflows with Nx | Nx Blog Autonomous Agents at Scale | Nx Blog Scaling 700+ Projects: How Nx Became a 'No-Brainer' for Caseware | Nx Blog Configure Tailwind v4 with Angular in an Nx Monorepo | Nx Blog The Missing Multiplier for AI Agent Productivity | Nx Blog A Year of Nx Webinars | Nx Blog Wrapping Up 2025 | Nx Blog Nx 22.3 Release: Angular 21 Support, tsgo Compiler, and Prettier v3 | Nx Blog Nx Cloud Release: Agent Resource Usage | Nx Blog Nx Platform Outperforms DIY Cache by 5x | Nx Blog An Nx Carol: Past, Present, and Future of Your Monorepo | Nx Blog Nx 22.1 Release: Terminal UI on Windows, Storybook 10, Vitest 4, and more! | Nx Blog The Compounding Effect: How Nx Features Multiply Performance Gains | Nx Blog 10 Monorepo Myths Debunked: Separating Fact from Fiction | Nx Blog Nx Cloud Release: Enterprise Task Analytics | Nx Blog Watch and Rebuild Storybook Dependencies with Nx | Nx Blog Book - React for Enterprise: Timeless Architecture for Enterprise Apps | Nx Blog Beyond Remote Cache: Unlock 70% More CI Performance | Nx Blog Nx 22 Release: Expanding the build platform | Nx Blog What's the Point of Generating All This Code If You Can't Merge It? | Nx Blog
Handling CORS In Your Workspace | Nx Blog
Mike Hartington · 2024-11-15 · via Nx Blog

CORS - The Great Initiation For Web Developers

Are you even a developer if you've never dealt with CORS? Jokes aside, CORS is one of those problems that everyone faces at least once in their life, and if it's your first time, it can be quite frustrating. CORS stands for Cross Origin Resource Sharing, which is a mechanism for allowing what URLs can access other URLs. Meaning if I have http://site1.com and I try to access something from http://site2.com, I will get an Access-Control-Allow-Origin error.

To demonstrate the issue most developers will encounter with CORS, take this example: I have a web server that I'm hosting locally on port 3333. This is a typical REST API that I can make a request to and get a response back:

REST API returning the data as expected

That's working as expected, but now consider trying to make this request from a different origin. When I try to make my request in my web app, the request will fail:

REST API blocking the request in the bowser

This is due to CORS restriction that is actually built into our browser. Whenever you make a network request from one location (in this case, our Angular App that is hosted on http://localhost:4200) to a different location (the API hosted at http://localhost:3333), the browser will intercept this request, and if the API hasn't allowed requests from localhost:4200, it will block the request.

Letting The Request Through

Now CORS-related issues can be addressed in multiple ways, and it can be as simple as bypassing CORS all together (the less ideal solution) or configuring a middleware for our dev server to intercept any requests.

But wait, I thought Nx would do this for me?

In past releases, Nx would provide options in our executors to configure a proxy connection between backend and frontend applications. This still exists for example in our Angular plugin where we are still using executors. However, with our decision to move to a more "optionally opinionated" approach, we now recommend that you use native CLI tools (like vite or webpack) instead of our executors. In this approach, you'd configure the proxy exactly according to how the tool prescribes. Nx doesn't get in your way!

To address this, our two possible solutions could be at the API level, or the framework level.

Handle The CORS Request On The API

Let's take this very basic Express app that you can get when you run our default Express app generator from @nx/express:

main.ts

import express from 'express';
import * as path from 'path';
const app = express();

app.use('/assets', express.static(path.join(__dirname, 'assets')));

app.get('/api', (_req, res) => {
  res.send({ message: 'Welcome to api!' });
});

const port = process.env.PORT || 3333;
const server = app.listen(port, () => {
  console.log(`Listening at <http://localhost>:${port}/api`);
});
server.on('error', console.error);

There are two ways we can address CORS in our API. One approach can be to actually set the Access-Control-Allow-Origin header in our request:

main.ts

app.get('/api', (_req, res) => {
  res
    .setHeader('Access-Control-Allow-Origin', '*')
    .send({ message: 'Welcome to api!' });
});

Or, we can use the cors middleware.

npm install cors @types/cors

With cors installed, you can import the package and use it in your app:

main.ts

  import express from 'express';
  import * as path from 'path';
+ import cors from 'cors'

  const app = express();

+ app.use(cors())

By just doing this, any requests made to our Express API will allow all requests, but you can limit it to certain origins by passing in some options to cors()

main.ts

app.use(
  cors({
    origin: '<http://example.com>',
  })
);

Now, why would you use the cors middleware when you could just set the Access-Control-Allow-Origin header yourself? The middleware handles a lot of edge cases that you would need to write yourself, and at sub 250 lines of code, it doesn't add too much to your codebase.

Leave It To The Framework Tools

If you don't have control over the API and are not able to enable CORS, there's still another option for you. Most framework tools have an option to let you pass a proxy file to your dev server. Then any requests made during development can be proxied by the dev server, and you can continue building your app.

For example, in our Angular application, let's create a proxy.conf.json in our web project:

touch apps/web/src/proxy.conf.json

In that file, let's add the following:

proxy.conf.json

{
  "/api": {
    "target": "http://localhost:3333",
    "secure": false
  }
}

Then in our in the project.json, let's tell the dev server about this newly created proxy file:

project.json

    "serve": {
      "executor": "@angular-devkit/build-angular:dev-server",
+     "options":{
+       "proxyConfig": "apps/web/src/proxy.conf.json"
+     },

With our dev server running, we can simply make requests to /api and the request will be allowed.

For frameworks like Vue and React that provide a Vite config, you can inline this right in the config:

vite.config.ts

export default defineConfig({
  server: {
    proxy: {
      '/api': {
        target: 'http://localhost:3333',
      },
    },
  },
});

Parting Thoughts

With CORS being an ever present issue in many apps, it's important to know how to address it when you run into it. By either addressing it at the API level or with in your app directly, you can make sure that CORS doesn't stop you from shipping your projects.