首页 > 解决方案 > “TypeError:无法读取未定义的属性‘替换’”

问题描述

我一直在尝试制作我的第一个 express 应用程序,但 range.replace() 出现错误,我尝试搜索修复程序,但找不到修复程序,这在我尝试流式传输视频时发生。这是我第一次使用 express 所以忽略 app.send() 的 html 脚本 :)

我的代码是:

const express = require('express');
const app = express();
const fs = require('fs')
const path = require('path')
require('dotenv').config();
const { auth, requiresAuth } = require('express-openid-connect');

app.use(
    auth({
        authRequired: false,
        auth0Logout: true,
        issuerBaseURL: process.env.ISSUER_BASE_URL,
        baseURL: process.env.BASE_URL,
        clientID: process.env.CLIENT_ID,
        secret: process.env.SECRET,
    })
);

app.get('/profil', requiresAuth(), (req, res) => {
    const profileJSON = JSON.stringify(req.oidc.user);
    var obj = JSON.parse(profileJSON);
    function emailVerified(){
        if (obj.email_verified == "true"){
            return "Doğrulandı";
        }
        else {
            return "Doğrulanmadı";
        }
    }
    res.send(
        `
        <!DOCTYPE html>
        <head>
            <title>Profil sayfası</title>
        </head>
        <body>
            <h1>${obj.nickname}</h1>
            <img src="${obj.picture}"></img>
            <h2>Gerçek isim: ${obj.name}</h2>
            <h2>E-posta: ${obj.email}</h2>
            <h2>E-Posta Doğeulanma Durumu: ${obj.email_verified}</h2>
            <h2>Ülke: ${obj.locale}<h2>
        </body>
        `
    );
})


app.get('/', (req, res)=>{
    res.send(req.oidc.isAuthenticated() ? `
    <!DOCTYPE html>
    <head>
        <title>Murat Ödev Sayfası</title>
    </head>
    <body>
        <h1>Murat Ödev Sayfası</h1>
        <h2>Giriş Durumu: Giriş yapıldı<h2><a href="/logout">Çıkış yap</a>
        <a href="/profil">Profil sayfası</a>
        <a href="/video">Video test</a>
    </body>
    ` : `
    <!DOCTYPE html>
    <head>
        <title>Murat Ödev Sayfası</title>
    </head>
    <body>
        <h1>Murat Ödev Sayfası</h1>
        <h2>Giriş Durumu: Giriş yapılmadı<h2><a href="/login">Giriş yap</a>
    </body>
    `)
})


app.get('/video', requiresAuth(),(req, res) => {
    const range = req.headers.range;
  if (!range) {
    res.status(400).send("Requires Range header");
  }

  // get video stats (about 61MB)
  const videoPath = "video.mp4";
  const videoSize = fs.statSync("video.mp4").size;

  // Parse Range
  // Example: "bytes=32324-"
  const CHUNK_SIZE = 10 ** 6; // 1MB
  const start = Number(range.replace("/\D/g", ""));
  const end = Math.min(start + CHUNK_SIZE, videoSize - 1);

  // Create headers
  const contentLength = end - start + 1;
  const headers = {
    "Content-Range": `bytes ${start}-${end}/${videoSize}`,
    "Accept-Ranges": "bytes",
    "Content-Length": contentLength,
    "Content-Type": "video/mp4",
  };

  // HTTP Status 206 for Partial Content
  res.writeHead(206, headers);

  // create video read stream for this particular chunk
  const videoStream = fs.createReadStream(videoPath, { start, end });

  // Stream the video chunk to the client
  videoStream.pipe(res);
})

const port = process.env.PORT || 3000;
app.listen(port, () => {
    console.log(`Listening on port ${port}`);
})

错误是:

TypeError: Cannot read property 'replace' of undefined

我希望有人可以帮助我

标签: javascriptnode.jsexpress

解决方案


您执行以下操作以查看是否定义了范围

if (!range) {
  res.status(400).send("Requires Range header");
}

您正在正确查找错误情况,但这里的问题是您没有退出,因此它继续,因此您收到错误的原因。添加return退出函数

if (!range) {
  res.status(400).send("Requires Range header");
  return;
}

推荐阅读