如何解决UnauthorizedError: Format is Authorization: Bearer [token] - Vue 3 and Apollo Server, Express, jsonwebtoken, express-jwt
我有一个 Vue 3 应用程序和一个 Apollo & Express 服务器。 当我想与后端通信时,我遇到了这些问题(请查看下方):
UnauthorizedError: Format is Authorization: Bearer [token]
at middleware (/Users/user/vscode/gestion-subvention-api/node_modules/express-jwt/lib/index.js:73:21)
at Layer.handle [as handle_request] (/Users/user/vscode/gestion-subvention-api/node_modules/express/lib/router/layer.js:95:5)
at trim_prefix (/Users/user/vscode/gestion-subvention-api/node_modules/express/lib/router/index.js:317:13)
at /Users/user/vscode/gestion-subvention-api/node_modules/express/lib/router/index.js:284:7
at Function.process_params (/Users/user/vscode/gestion-subvention-api/node_modules/express/lib/router/index.js:335:12)
at next (/Users/user/vscode/gestion-subvention-api/node_modules/express/lib/router/index.js:275:10)
at cors (/Users/user/vscode/gestion-subvention-api/node_modules/cors/lib/index.js:188:7)
at /Users/user/vscode/gestion-subvention-api/node_modules/cors/lib/index.js:224:17
at originCallback (/Users/user/vscode/gestion-subvention-api/node_modules/cors/lib/index.js:214:15)
at /Users/user/vscode/gestion-subvention-api/node_modules/cors/lib/index.js:219:13
createHttpLink.js?a012:93 POST http://localhost:4000/graphql 401 (Unauthorized)
eval @ createHttpLink.js?a012:93
Subscription @ Observable.js?a7b2:197
subscribe @ Observable.js?a7b2:279
complete @ Concast.js?5549:57
Concast.start @ Concast.js?5549:83
Concast @ Concast.js?5549:75
QueryManager.getobservableFromLink @ QueryManager.js?cb44:487
eval @ QueryManager.js?cb44:85
eval @ QueryManager.js?cb44:82
step @ tslib.es6.js?9ab4:100
eval @ tslib.es6.js?9ab4:81
eval @ tslib.es6.js?9ab4:74
__awaiter @ tslib.es6.js?9ab4:70
QueryManager.mutate @ QueryManager.js?cb44:47
ApolloClient.mutate @ ApolloClient.js?365c:139
eval @ useMutation.js?89f9:96
step @ useMutation.js?89f9:43
eval @ useMutation.js?89f9:24
eval @ useMutation.js?89f9:18
__awaiter @ useMutation.js?89f9:14
mutate @ useMutation.js?89f9:66
eval @ Login.vue?5326:83
eval @ runtime-dom.esm-bundler.js?830f:1147
callWithErrorHandling @ runtime-core.esm-bundler.js?5c40:154
callWithAsyncErrorHandling @ runtime-core.esm-bundler.js?5c40:163
invoker @ runtime-dom.esm-bundler.js?830f:333
index.js?3ca0:26 Uncaught (in promise) Error: Unexpected token < in JSON at position 0
at new ApolloError (index.js?3ca0:26)
at Object.error (QueryManager.js?cb44:127)
at notifySubscription (Observable.js?a7b2:140)
at onNotify (Observable.js?a7b2:179)
at SubscriptionObserver.error (Observable.js?a7b2:240)
at eval (iteration.js?fceb:4)
at Array.forEach (<anonymous>)
at iterateObserveRSSafely (iteration.js?fceb:4)
at Object.error (Concast.js?5549:36)
at notifySubscription (Observable.js?a7b2:140)
Vue 3
应用程序 main.ts 代码是:
import { createApp,h,provide } from "vue";
import App from "./App.vue";
import "@/assets/css/tailwind.css";
import router from "./router";
import store from "./store";
import {
ApolloClient,ApolloLink,InMemoryCache,from,HttpLink,} from "@apollo/client/core";
import { ApolloClients } from "@vue/apollo-composable";
const my_token = localStorage.getItem("gest_sub_token");
const additiveLink = from([
new ApolloLink((operation,forward) => {
operation.setContext(({ headers }: { headers: any }) => ({
headers: {
...headers,authorization: my_token ? `Bearer ${my_token}` : null,},}));
return forward(operation);
}),new HttpLink({ uri: process.env.VUE_APP_API_URL }),]);
const apolloClient = new ApolloClient({
link: additiveLink,cache: new InMemoryCache(),});
const app = createApp({
setup() {
provide(ApolloClients,{
default: apolloClient,});
},render: () => h(App),});
app.use(store).use(router).mount("#app");
Apollo 服务器 app.ts 代码为:
import { ApolloServer } from 'apollo-server-express';
import express from 'express';
import cors from 'cors';
import { join } from 'path';
import { typeDefs,resolvers } from './graphql';
import { JWT_CREDENTIALS,URL,IN_PROD } from './config/env-config';
import morgan from 'morgan';
const app = express();
app.use(express.static(join(__dirname,'./uploads')));
app.use(morgan('dev'));
app.use(cors());
app.use(JWT_CREDENTIALS);
const server = new ApolloServer({
typeDefs,resolvers,playground: IN_PROD,context: ({ req }) => {
const user = req.user || null;
return { user };
},});
server.applyMiddleware({ app });
app.listen(process.env.APP_PORT,() => {
console.log(`server ready at ${URL}${server.graphqlPath}`);
});
JWT_Credentials 是:
const JWT_CREDENTIALS = jwt({
secret: privateKey,algorithms: ['HS256'],credentialsrequired: false,});
我收到 401 Unauthorized 但是当我使用 GraphQL playground 时它工作正常。不知道问题出在服务器端还是客户端。
有人可以帮我处理这个问题吗?
解决方法
这个问题很容易解决。这是由于在检查他在 localStorage 中的值后分配给 my_token 的值:
authorization: my_token ? `Bearer ${my_token}` : null,
解决它的正确方法是分配一个空字符串``
或""
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。