Home > Software engineering >  I'm learning webpack and I'm trying to make an api call, but it's not working. Here&#
I'm learning webpack and I'm trying to make an api call, but it's not working. Here&#

Time:11-03

This is the server

const dotenv = require('dotenv');
dotenv.config();

// Configuring environment variables
const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const mockAPIResponse = require('./mockAPI.js');
const axios = require('axios');

const PORT = 8081;

const API_URL = 'https://api.meaningcloud.com/sentiment-2.1';

const apiKey = process.env.API_KEY


// Start an instance for the server
const app = express();

// Cors for cors-origin allowance
app.use(cors());

// Configuring express to use body-parser as middle-ware.
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

// Configure express static directory.
app.use(express.static('dist'));

app.get('/', function (req, res) {
    // res.sendFile('dist/index.html')
    res.sendFile(path.resolve('src/client/views/index.html'))
});

app.post('/add-url', async (req, res) => {

    const userInput = req.body.url
    const URL = `${API_URL}?key=${apiKey}&url=${userInput}&lang=en`
    console.log(URL)
    try {
        const data = await axios(URL)
        // console.log(data)
        res.json({
            // text: data.sentence_list[0].text,
            score_tag: data.score_tag,
            agreement: data.agreement,
            subjectivity: data.subjectivity,
            confidence: data.confidence,
            irony: data.irony
        })
        return data
    }

    catch (error) {
        console.log(error.message)
        res.json({
            status: 'error',
            message: 'Error: failed to fetch data'
        })
    }
});

app.get('/test', function (req, res) {
    res.send(mockAPIResponse)
})

// Setup Server
app.listen(PORT, (error) => {
    if (error) throw new Error(error)
    console.log(`Server listening on port ${PORT}!`)
})

and this is the client side

client/formHandler

import { checkURL } from "./checkURL"

const post = async (url = '', data = {}) => {
    const response = await fetch(url, {
        method: 'POST',
        credentials: 'same-origin',
        mode: 'cors',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(data)
    })

    try {
        return await response.json()
    }
    catch (error) {
        console.log('error', error)
    }
}

const handleSubmit = async (event) => {
    event.preventDefault()
    
    const url = document.getElementById('article-url').value
    // console.log(url)

    if(checkURL(url)) {
        post('http://localhost:8081/add-url', {url}).then(data => {

            document.getElementById('text').innerHTML = `Text: ${data.text}`
            document.getElementById('score_tag').innerHTML = `Polarity: ${data.score_tag}`
            document.getElementById('agreement').innerHTML = `Agreement: ${data.agreement}`
            document.getElementById('subjectivity').innerHTML = `Subjectivity: ${data.subjectivity}`
            document.getElementById('confidence').innerHTML = `Confidence: ${data.confidence}`
            document.getElementById('irony').innerHTML = `Irony: ${data.irony}`
            // console.log(data)
        })

    }

    else {
        alert('Please enter a valid URL')
    }

}

export default handleSubmit

client/index.js

import handleSubmit from './js/formHandler';
import { checkURL } from './js/checkURL';



window.addEventListener('DOMContentLoaded', () => {
    
    const buttonSubmit = document.querySelector('.btn-submit')
    buttonSubmit.addEventListener("click", () => {
        handleSubmit()
    })
})

export {
    checkURL,
    handleSubmit
}

client/index.html

  <body>
    <main>
      <div class="container">
        <p>Enter a URL of an article / a blog to discover its sentiment.</p>
        <section>
          <form id="form" onsubmit="return Client.handleSubmit(event)">
            <label for="article-url">URL</label>
            <input id="article-url" type="text" name="input" value="" placeholder="Enter Article URL here" />
            <button
              type="submit"
              class="btn-submit"
            >
              Submit
            </button>
          </form>
        </section>

        <section>
          <strong>Form Results:</strong>
          <div id="text"></div>
          <div id="agreement"></div>
          <div id="subjectivity"></div>
          <div id="confidence"></div>
          <div id="irony"></div>
          <div id="score_tag"></div>
        </section>
      </div>
    </main>
    <script>
      // Check that service workers are supported
      if ('serviceWorker' in navigator) {
        // Use the window load event to keep the page load performant
        window.addEventListener('load', () => {
          navigator.serviceWorker.register('/service-worker.js')
        })
      }
    </script>
  </body>

Here are the errors I get:

1- in the console

Uncaught TypeError: buttonSubmit.addEventListener is not a function "at index.js:10"

and the attached image is the result in the index.htmlenter image description here

If someone can provide me with any solution to this problem. I'm new at both webpack and API

CodePudding user response:

Try this.

const buttonSubmit = document.querySelector('.btn-submit')
 
if( document.readyState !== 'loading' ) {
    console.log( 'document is already ready, just execute code here' );
    buttonSubmit.addEventListener("click", () => {
        handleSubmit()
    })
} else {
    document.addEventListener('DOMContentLoaded', function () {
        console.log( 'document was not ready, place code here' );
        buttonSubmit.addEventListener("click", () => {
           handleSubmit()
        })
    });
}

IMO it is not required to use DOMContentLoaded, you can include your index.js at last of your index.html with a defer tag.

<script src="./index.js" defer />
  • Related