簡體   English   中英

表達錯誤:SyntaxError: Unexpected token ':'

[英]Express error: SyntaxError: Unexpected token ':'

很少在這里發帖。 如果我的帖子遺漏了什么,我深表歉意。

這是我的第一個 API 和 Express 和 node.js。 下面的代碼產生以下... SyntaxError: Unexpected token ':'

嘗試移動冒號空格並用等號替換冒號,但顯然這些不是解決此問題的方法。

簡化了 app.get() 方法以在瀏覽器頁面上生成字符串 output 並且效果很好。 但是,當我嘗試在向瀏覽器發送字符串之外實際做任何有意義的事情時,我會從 express 中收到此錯誤,這會導致應用程序崩潰。 使用 sublime 文本編輯器,它在括號和括號的結束對上顯示紅色突出顯示。 有什么幫助嗎?

const axios = require('axios')
const app = express()

app.get('/fitaid', (req,res) => { 

    axios.get('https://www.lifeaidbevco.com/apparel') 
      .then((response : AxiosResponse<any>) => {
        const html = response.data
        console.log(html)
    })
})

嘗試使用下面的代碼,它會更簡單,更容易理解您的代碼

app.get('/fitaid', async (req,res) => {
    const response = await axios.get('https://www.lifeaidbevco.com/apparel');
    console.log(response.data.html);
});

正如我在評論中所說,這看起來像是由您使用的 TypeScript 語法引起的錯誤,所以我猜您要么不打算使用 TypeScript 語法,您需要轉換為普通的 Z9E13B69D1D24AAAAF270 語法或出於某種原因,您沒有在運行之前將 TypeScript 編譯為 Javascript 。

如果您打算只編寫和運行普通的 Javascript,則刪除回調聲明中的類型信息並更改:

const axios = require('axios')
const app = express()

app.get('/fitaid', (req,res) => { 

    axios.get('https://www.lifeaidbevco.com/apparel') 
      .then((response : AxiosResponse<any>) => {
        const html = response.data
        console.log(html)
    })
})

對此:

const axios = require('axios')
const app = express()

app.get('/fitaid', (req,res) => { 

    axios.get('https://www.lifeaidbevco.com/apparel').then((response) => {
        const html = response.data;
        console.log(html);
        res.send(html);
    }).catch(err => {
        console.log(err);
        res.sendStatus(500);
    });
});

另外,請注意,您必須在請求處理程序中發送某種類型的響應。 目前,您只顯示輸出到控制台而不發送響應。

而且,您應該從axios()調用中捕獲任何錯誤並發送錯誤響應。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM