Home  >  Q&A  >  body text

How to send markdown via REST API and render it on the frontend (React)

So I tried converting the Markdown file and sending it via Rest API and then rendering it on the frontend. The problem is that newlines and other content are lost when trying to convert them back.

How do I render it in a way that preserves the original markdown?

Is there a standard way to do this?

Tried converting markdown via json.stringify, sent via api, tried converting it back to markdown, but no longer works like the original.

P粉166779363P粉166779363207 days ago318

reply all(2)I'll reply

  • P粉418214279

    P粉4182142792024-02-27 10:52:54

    You can add everything in

     tag as following

       This is
       some code
       Ajson:
       {
         key: value
       }
    

    In <pre> tags, the text preserves spaces and newlines, so it will appear exactly as written in the HTML source code.

    reply
    0
  • P粉423694341

    P粉4236943412024-02-27 00:41:39

    You can send the original file as a string, or if this is not an option, you can use this function to format the object:

    const object = {a:[15,3457,15,"afbsv",[4,34,36],{
      l: "dsfvszd",
      qwe: 238475463,
      iuggbsf: ["AEfs",],
      afafwwa:{afafwafaw:{r:"4"}}
    }]}
    
    document.write(`
    ${format(object)}
    `); function format (object) { let result = ""; ProcessObject(Object, 2); Function processObject(object, depth, isObjectValue = false, TrailingComma = "") { if (array . isArray (object)) { Result = `${isObjectValue ? " " : "
    " " ".repeat(depth - 2)}[`; for (let i = 0; i < object.length; i ) { const element = object[i], TrailingComma = i 1 === object.length ? "": ","; switch (element type) { Case "object": processObject(element, depth 2, false, TrailingComma); rest; Case "string": Result = `< object.length; i++) { const 元素 = 对象[i], TrailingComma = i + 1 === object.length ? “”:“,”; switch(元素类型){ 案例“对象”: processObject(元素, 深度 + 2, false, TrailingComma); 休息; 案例“字符串”: 结果 += `
    ${" ".repeat(depth)}"${element}"${trailingComma}`; rest; Case number": Result = `
    ${" ".repeat(depth) element}${trailingComma}`; rest; } } Result = `
    ${" ".repeat(depth - 2)}]${trailingComma}`; } other { Result = `${isObjectValue ? " " : "
    " " ".repeat(depth - 2)}{`; Let keyIndex = 0, keyCount = Object.keys(object).length; for (key in object) { constant value = object[key], Trailing comma = keyIndex === keyCount ? "": ","; switch (value type) { Case "object": Result = `
    ${" ".repeat(depth)}"${key}":`; processObject(value, depth2, true, TrailingComma); rest; Case "string": Result = `
    ${" ".repeat(depth)}"${key}": "${value}"${trailingComma}`; rest; Case number": Result = `
    ${" ".repeat(depth)}"${key}": ${value}${trailingComma}`; rest; } } Result = `
    ${" ".repeat(depth - 2)}}${trailingComma}`; } } return results; }

    reply
    0
  • Cancelreply