
























什么是跨域问题
http://example1.com中的 JavaScript 代码尝试去获取http://example2.com的数据,这就会触发跨域问题。排查步骤
fetch或XMLHttpRequest的函数中,仔细检查请求的 URL。const xhr = new XMLHttpRequest();
xhr.open('GET', 'http://otherdomain.com/api/data');
xhr.send();
http://otherdomain.com与当前页面的域名不同。Access - Control - Allow - Origin字段。这个字段用于指定哪些域名可以访问该资源。Access - Control - Allow - Origin为*,则表示允许任何域名访问;如果是一个具体的域名,如http://allowed - domain.com,则只有这个域名下的网页可以访问。Access - Control - Allow - Origin、Access - Control - Allow - Methods(允许的请求方法,如 GET、POST 等)和Access - Control - Allow - Headers(允许的请求头)等字段。const express = require('express');
const cors = require('cors');
const app = express();
app.use(cors());
// 或者可以自定义配置
app.use(cors({
origin: 'http://allowed - domain.com',
methods: ['GET', 'POST'],
allowedHeaders: ['Content - Type']
}));
const headers = new Headers();
headers.append('Custom - Header', 'value');
fetch('https://cross - domain - url.com/api', {
method: 'GET',
headers: headers
});
或者在使用XMLHttpRequest时:
const xhr = new XMLHttpRequest();
xhr.open('GET', 'https://cross - domain - url.com/api');
xhr.setRequestHeader('Custom - Header', 'value');
xhr.send();
Custom - Header)和值(如value),并记录下来。Access - Control - Allow - Headers响应头。这个头信息应该包含允许的请求头列表。Access - Control - Allow - Headers中,就会导致跨域问题。例如,服务器返回的Access - Control - Allow - Headers为Content - Type,Authorization,但你的自定义请求头是Custom - Header,这种情况下就会出现跨域错误。检查服务器端代码(如果可访问)
cors模块可以这样配置:Custom - Header添加到了允许的请求头列表中,这样就可以正确处理带有该自定义请求头的跨域请求。Access - Control - Allow - Headers包含自定义请求头,同时还应该返回Access - Control - Allow - Methods包含实际请求(如 GET、POST 等)将要使用的方法,以及Access - Control - Allow - Origin允许请求的来源域名。Access - Control - Allow - Origin: http://your - origin - domain.com
Access - Control - Allow - Methods: GET,POST
Access - Control - Allow - Headers: Content - Type,Custom - Header
此内容由惯性聚合(RSS阅读器)自动聚合整理,仅供阅读参考。 原文来自 — 版权归原作者所有。