我需要使用需要用户基本身份验证的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(),
});
请支持我将“授权”标头粘贴到请求中,或者了解使用“默认浏览器身份验证提示”的另一种方法。
使用: “ apollo-boost”:“ ^ 0.1.22”, “ apollo-link-context”:“ ^ 1.0.12”,
============================================ >
============================================ >
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(),
});
============================================ >
============================================ >
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(),
});
============================================ >
============================================ >
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(),
});
答案 0 :(得分:0)
BAP -浏览器授权提示
我花了很多时间找到解决方案:
我以这种方式创建了apollo-client
import gql from 'graphql-tag';
import { ApolloClient, ApolloLink, HttpLink, InMemoryCache, FetchPolicy } from 'apollo-boost';
import { onError } from 'apollo-link-error';
const errorLink = onError(({ graphQLErrors, networkError }) => {
if (graphQLErrors) {
graphQLErrors.map(({ message, locations, path }) =>
console.error(
`[GraphQL error]: Message: ${message}, Location: ${locations}, Path: ${path}`,
),
);
}
if (networkError) {
logger.error(`[Network error]: ${networkError}`);
}
});
const links: any = [];
links.push(errorLink);
links.push(
new HttpLink({
uri: process.env.REACT_APP_GQL_SERVER,
headers: {
authorization: 'Basic ' + btoa('<login>:<password>')
},
}),
);
const client = new ApolloClient({
link: ApolloLink.from(links),
cache: new InMemoryCache(),
});
如果您看到其他解决方案,请帮助您找到最佳的方法:)