我在连接redis时遇到了问题
**注意:**我使用安全连接,即rediss
。
当我做以下事情时,
// src/redis-client.js
const { createClient } = require('redis');
const redisClient = createClient({
url: REDIS_URL, // can be found in Vercel KV store
});
redisClient.on('error', (error) => {
console.error('Redis Error:', error);
});
redisClient.connect();
module.exports = redisClient;
个字符
然后在终端node test-redis.js
中运行以下命令
但是当我尝试在nextjs环境中这样做时,
import { createClient } from 'redis';
console.log(process.env.REDIS_URL) // This prints the correct URL
const redisClient = createClient({ url: process.env.REDIS_URL }); // this is where it fails
redisClient.on('error', (error) => {
console.error('Redis Error:', error);
});
redisClient.connect();
export default redisClient;
型
最终得到以下错误
- event compiled client and server successfully in 2.7s (3788 modules)
- error Error [TypeError]: url_1.URL is not a constructor
at <unknown> (webpack-internal:///(middleware)/./node_modules/@redis/client/dist/lib/client/index.js:86)
at Function.parseURL (webpack-internal:///(middleware)/./node_modules/@redis/client/dist/lib/client/index.js:86:76)
at Commander._RedisClient_initiateOptions (webpack-internal:///(middleware)/./node_modules/@redis/client/dist/lib/client/index.js:394:27)
at new RedisClient (webpack-internal:///(middleware)/./node_modules/@redis/client/dist/lib/client/index.js:202:148)
at new Commander (webpack-internal:///(middleware)/./node_modules/@redis/client/dist/lib/commander.js:46:13)
at create (webpack-internal:///(middleware)/./node_modules/@redis/client/dist/lib/client/index.js:82:16)
at createClient (webpack-internal:///(middleware)/./node_modules/redis/dist/index.js:78:38)
at eval (webpack-internal:///(middleware)/./src/redis-client.ts:8:72)
at Module.(middleware)/./src/redis-client.ts (file:///Users/shreyas/Desktop/planet-webapp/.next/server/middleware.js:6408:1)
at __webpack_require__ (file:///Users/shreyas/Desktop/planet-webapp/.next/server/edge-runtime-webpack.js:37:33)
at fn (file:///Users/shreyas/Desktop/planet-webapp/.next/server/edge-runtime-webpack.js:268:21) {
digest: undefined
}
型
这与nextjs在edge-runtime中运行代码有关吗?
当我在nextjs中使用dotenv包时,我遇到了类似的问题,它说process.cwd不是一个函数,但当它在nodejs env中运行时,它工作了。
1条答案
按热度按时间uujelgoq1#
这与运行时环境有关。
Nextjs代码在edge-runtime中运行,因此我们在错误的结尾处得到以下内容
字符串
据我所知,
redis
作为一个包并不是设计来运行在边缘运行时环境中的,在这个环境中更适合运行以连接到redis的包是@upstash/redis和@vercel/redis。