【发布时间】:2021-08-21 19:19:10
【问题描述】:
我有一个 Vue 3 应用程序和一个 Apollo & Express 服务器。 当我想与后端通信时,我遇到了这些问题(请查看下方):
Morgan 在终端上显示的后端错误:
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 App 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 游乐场时它工作正常。不知道问题出在服务器端还是客户端。
有人可以帮我处理这个问题吗?
【问题讨论】:
标签: express jwt vuejs3 apollo-server vue-apollo