'Express error: SyntaxError: Unexpected token ':'

Posting here is infrequent. I apologize if my post is missing something.

This is my first API with Express and node.js. The code below is producing the following...SyntaxError: Unexpected token ':'

Tried moving the colon white space and replacing colon with equal sign but apparently those are not resolutions to this issue.

Simplified the app.get() method to produce a string output on the browser page and that works perfectly. However, when I try to actually do anything meaningful outside of sending a string to the browser I am getting this error back from express which causes the app to crash. Using sublime text editor and it shows red highlights on the closing pairs of bracket and parenthesis. Any help?

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)
    })
})


Solution 1:[1]

As I said in my comment, this looks like an error caused by the TypeScript syntax you're using so I'm guessing that you either didn't intend to use TypeScript syntax and you need to convert to plain Javascript syntax or for some reason, you aren't compiling your TypeScript into Javascript before running it.

If you intend to just write and run plain Javascript, then remove the type information in the callback declaration and change this:

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)
    })
})

to this:

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);
    });
});

Also, note that you must send a response of some type in your request handler. Currently, you just show outputting to the console with no response being sent.

And, you should be catch any errors from your axios() call and sending an error response.

Solution 2:[2]

try with the below code, it will be simpler and easier to understand your code

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 jfriend00
Solution 2 TranTrung