Error: Import statement is not allowed outside of module scope

I've been through multiple documentations and sources, but I'm still struggling to fix this error. I recently started learning JavaScript and decided to experiment with fetch() commands, however, I keep encountering an issue (the title).

Below is my code:

index.js

import fetch from 'node-fetch';

fetch('http://example.com/movies.json')
  .then(response => response.json())
  .then(data => console.log(data));


package.json

{
  "name": "Weather-API",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "type": "module",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "node-fetch": "^3.0.0"
  }
}

Answer №1

According to the feedback from Chris G, this code is functioning correctly.

Code:

fetch('https://jsonplaceholder.typicode.com/posts/1')
      .then(response => response.json())
      .then(data => console.log(data));

Output:

{
    "userId": 1,
    "id": 1,
    "title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
    "body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
}

Kindly remove the import line and give it another try. If it still doesn't work, please verify your node version - I have successfully tested it with version 14.17.0.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How can you enable a button to be clicked from within a drawer?

Hey there, I've got a div that toggles hide/show like a drawer when clicked. When the drawer is in show state, it contains a button. How can I make the button clickable without toggling the drawer? Any ideas on this?! `zIndex` doesn't seem to be ...

Encountered an error with code ERR_OSSL_PEM_NO_START_LINE along with the message "routines:get_name:no start line" while trying

I ran into an issue while trying to set up react, where the installation process kept aborting. I am using node v16-14-0 and npm v6-14-11. npx creat-react-app my-app npx: installed 67 in 13.6s creating a new react app in C:\User\adminstrator&bso ...

A guide on consolidating all app.use statements into a single shared file

My application's starting point, the index file, contains multiple instances of app.use. For example: app.use( if (!req.contextToken && req.contextTokenchecked) { req.queryToFirebase = false; req.contextTokenchecked = tru ...

SortTable - Refresh Dropdown Filter in Header After Adding Row to Table

My tablesorter table initially displays two entries in the "License" Filter. If I dynamically add a row, the table now looks like this: I have attempted to update the table using the following commands: $('#connectionGrid2').trigger('upda ...

Expand Bootstrap accordion on hover

I have tried several examples that I discovered on Google and Stack Overflow, but none of them seem to work. So, I decided to attempt a different solution for opening the Bootstrap accordion on hover, however, it is not working as expected. Do you have any ...

What is the benefit of using an IIFE in this particular way when constructing a JavaScript library?

Many libraries I've seen use a similar style to define their structure. Upon further inspection, I've noticed that the first self-invoking function is often related to Require.js or AMD systems, with 'factory' as an argument. My curiosi ...

Utilizing an object as a prop within React-router's Link functionality

Looking for a solution to pass the entire product object from ProductList component to Product component. Currently, I am passing the id as a route param and fetching the product object again in the Product component. However, I want to directly send the ...

Understanding the scope of jQuery variables within a function

myClass.prototype.toggle = function() { var elements = []; $.getJSON('http://localhost/jsoner.php', function(data) { $.each(data, function(index, value) { elements.push(value); alert(elements[0]); //this is functioning } ...

Checking the formik field with an array of objects through Yup for validation

Here is a snippet of the code I'm working on: https://codesandbox.io/s/busy-bose-4qhoh?file=/src/App.tsx I am currently in the process of creating a form that will accept an array of objects called Criterion, which are of a specific type: export inte ...

Is there an appropriate method in Vue/Nuxt for managing and altering component data without using lifecycle hooks?

Scenario: I am dealing with a component that showcases a datatable listing Applications. Upon clicking a row, it triggers the opening of another component with appropriately loaded fields (for new or edit). The Challenge: The component loads a reference t ...

Collect user input from an array of checkboxes

After spending hours attempting to retrieve data from an array of checkboxes with the same name, I am still facing difficulties. <input type="checkbox" name="node"/> var selectedValues = []; $(document.getElementsByName("node")).each( ...

Utilizing web components from NPM packages in conjunction with Svelte

My current project involves the development of a simple Single Page App (SPA) using Svelte. I have successfully implemented a basic layout and styling, as well as an asynchronous web request triggered by a button click. Now, my next objective is to utiliz ...

How can I toggle input disablement in Bootstrap depending on switch selection?

I have been exploring the Bootstrap 5 documentation in search of a way to disable other input fields when a toggle switch input is set to 'off'. The parent element for this scenario is #member_form, and the switch itself is identified as 'to ...

Incorporating React into a non-React website

I am currently working on a project where the server renders all views using the Twig template engine. Therefore, I tend to write all my scripts within the .twig templates. Take, for instance, the aside-buttons.twig template: <div class="aside-butto ...

Getting some clarity on how to structure a project using Node.js, Express.js, and React.js

I am in the process of developing a website for online shopping purposes, essentially an e-commerce platform. However, I am facing a dilemma where create-react-app sets up its own Node.js server to communicate with my backend (which handles MySQL queries) ...

What role does NPM play in the deployment of a Node.js App with AWS Beanstalk?

I'm interested in the workflow of an AWS Beanstalk deployment, particularly regarding the installation of packages. I assume that npm is used during the process to install packages on the server(s). However, I am curious to know if AWS Beanstalk utili ...

Trouble with highlighting the chosen menu item

I have been attempting to implement this code snippet from JSFiddle onto my website. Although I directly copied the HTML, used the CSS inline, and placed the Javascript in an external file, the functionality does not seem to be working properly. Feel free ...

Ensuring a successful installation of SQLite for Node.js

I am currently trying to install SQLite for Node.js as per the following instructions: apt-get install sqlite3 apt-get install libsqlite3-dev npm install sqlite3 However, when I use the code snippet below: var db = new require('sqlite3').verbo ...

Creating dynamic canvas elements with images using HTML and JavaScript

Currently, I am working on a unique project involving a canvas filled with dynamic moving balls. This project is an extension or inspired by the codepen project located at: https://codepen.io/zetyler/pen/LergVR. The basic concept of this project remains t ...

Real-time preview of a text field in JavaScript

I'm attempting to create a similar piece of code like the one at the bottom of this page for leaving comments. I have the basic code, but the result doesn't display new lines (or HTML, although that's not essential). I have the function belo ...