本地Angular 6调用Node.js接口遭遇CORS错误求助
解决Angular 6与Node.js之间的CORS拦截问题
嘿,我一眼就揪出问题所在了——你遇到的这个CORS错误不是Node.js的CORS配置有问题,而是前端请求的URL犯了一个小错误!
先看错误信息里的关键部分:
Access to XMLHttpRequest at 'localhost:2000/products/create' from origin 'http://localhost:4200' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https.
注意到请求地址是localhost:2000/products/create,这里缺少了http://协议前缀!浏览器会把这种没有协议的地址当成非HTTP/HTTPS类的资源请求,而CORS规则只支持http、https等协议方案,所以直接触发了拦截。
第一步:修复Angular的请求URL
在你的Angular服务里,把请求URL改成带完整协议的地址就行:
// 修正后的URL,加上http://前缀 private url = 'http://localhost:2000/products/create'; register(regData){ return this.httpClient.post(this.url, regData); }
如果是把API基础地址抽离到环境配置里(更推荐的做法),可以这样改:
// src/environments/environment.ts export const environment = { production: false, apiBaseUrl: 'http://localhost:2000' }; // 在你的服务中引入并使用 import { environment } from '../environments/environment'; private url = `${environment.apiBaseUrl}/products/create`;
第二步:优化Node.js的CORS配置(可选但实用)
你的Node.js CORS配置其实没毛病,但可以加个小优化——允许Postman这类无origin标识的工具请求,方便测试:
var corsOptions = { origin: function(origin, callback){ // 白名单内的地址 + 无origin的请求(比如Postman)都允许 var isWhitelisted = originsWhitelist.indexOf(origin) !== -1 || !origin; callback(null, isWhitelisted); }, credentials:true } app.use(cors(corsOptions));
最后再检查两个小细节
- 确认Angular服务(
localhost:4200)和Node.js服务(localhost:2000)都在正常运行 - 后续部署到生产环境时,记得把白名单里的地址换成实际的前端域名
内容的提问来源于stack exchange,提问作者Ali
相关产品推荐
相关产品推荐

