我有一个create-react-app应用程序,通过添加以下内容来启用代理:
"proxy": "http://localhost:3001",
到我的package.json。对于/ graphql的API请求来说,这很好用,但是当Web浏览器请求/ graphql(用于加载UI以运行查询的目的)由前端处理而不是被代理时。是否也可以代理它?
当我尝试通过访问https://localhost:3000/auth/facebook进行OAuth时,也会发生同样的事情,前端会处理它而不是后端处理。
答案 0 :(得分:4)
确实有可能进一步自定义代理。
首先,当网络浏览器请求const orderData = [
{
id: 1,
title: 'Order 1',
date: '2020-06-15T18:05:43.040468',
type: 'Affectation',
},
{
id: 2,
title: 'Order 2',
date: '2020-06-15T18:05:55.397698',
type: 'Affectation',
},
{
id: 3,
title: 'Order 3',
date: '2020-05-15T18:06:15.853506',
type: 'Affectation',
},
{
id: 4,
title: 'Order 4',
date: '2020-03-15T18:06:44.421666',
type: 'Affectation',
},
{
id: 5,
title: 'Order 5',
date: '2020-05-15T18:06:44.421666',
type: 'Affectation',
},
{
id: 6,
title: 'Order 6',
date: '2020-01-15T18:07:03.856468',
type: 'Affectation',
},
{
id: 7,
title: 'Order 7',
date: '2020-02-15T20:09:25.164826',
type: 'Affectation',
},
{
id: 8,
title: 'Order 8',
date: '2020-03-15T20:09:25.164826',
type: 'Affectation',
},
];
// This function takes a string and creates a date object from the string and return the month.
const findMonth = (datestring) => {
let date = new Date(datestring);
return date.getMonth();
};
const makeDateArray = (orders) => {
let monthFreq = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; // you can use Array.fill() but for clarity
// now you loop over each object in the data array
for (const order of orders) {
const month = parseInt(findMonth(order.date));
// Months are from 0-11 in JS so it matches directly with array index
monthFreq[month] = monthFreq[month] + 1;
}
return monthFreq;
};
console.log(makeDateArray(orderData));
或/graphql
时,它会发送一个/auth/facebook
标头,其中包含Accept
(还有其他)。 CRA代理specifically ignores的配置使用以下标头值:
开发服务器将仅尝试将其Accept标头中没有text / html的请求发送到代理。
(强调原文)
幸运的是,您可以覆盖默认配置,并且基本上可以根据自己的喜好选择代理中间件。 There are detailed instructions in the docs,甚至在npm package docs中更是如此,但关键是:
text/html