【发布时间】:2019-07-01 06:21:35
【问题描述】:
我需要使用需要用户基本身份验证的 Graphql 开发服务器。
在前端向受保护的 graphql 服务发出请求,我编写了下一个代码
const authLink = setContext((_, { headers }) => {
return {
headers: {
...headers,
Authorization: 'Basic ' + btoa('<login>:<pass>'),
}
}
});
const httpLink = new HttpLink({
uri: process.env.REACT_APP_GQL_SERVER,
fetchOptions: {
mode: 'no-cors'
}
});
const client = new ApolloClient({
link: authLink.concat(httpLink),
cache: new InMemoryCache(),
});
您能否支持我将授权标头粘贴到请求中或了解使用默认浏览器身份验证提示的另一种方式。
使用: “阿波罗升压”:“^0.1.22”, "apollo-link-context": "^1.0.12",
==============================================
经过测试的变体放置标题 #1
==============================================
const httpLink = createHttpLink({
uri: process.env.REACT_APP_GQL_SERVER,
fetchOptions: {
mode: 'no-cors'
},
});
const middlewareLink = new ApolloLink((operation, forward: any) => {
operation.setContext({
headers: {
"Authorization": 'Basic ' + btoa('<login>:<password>')
}
});
return forward(operation);
});
const client = new ApolloClient({
link: middlewareLink.concat(httpLink),
cache: new InMemoryCache(),
});
==============================================
经过测试的变体放置标题 #2
==============================================
const authLink = setContext((_, { headers }) => {
return {
headers: {
...headers,
authorization: 'Basic ' + btoa('<login>:<password>'),
}
}
});
const httpLink = new HttpLink({
uri: process.env.REACT_APP_GQL_SERVER,
fetchOptions: {
mode: 'no-cors'
}
});
const links: any = [];
links.push(httpLink);
links.push(authLink);
const client = new ApolloClient({
link: ApolloLink.from(links),
cache: new InMemoryCache(),
});
==============================================
经过测试的变体放置标题 #3
==============================================
const middlewareLink = new ApolloLink((operation, forward: any) => {
operation.setContext({
headers: {
authorization: 'Basic ' + btoa('<login>:<password>')
}
});
return forward(operation);
});
const httpLink = new HttpLink({
uri: process.env.REACT_APP_GQL_SERVER,
fetchOptions: {
mode: 'no-cors'
}
});
const links: any = [];
links.push(httpLink);
links.push(middlewareLink);
const client = new ApolloClient({
link: ApolloLink.from(links),
cache: new InMemoryCache(),
});
【问题讨论】:
标签: javascript reactjs apollo react-apollo apollo-client