I’m trying to use GraalVM to execute JavaScript code that makes a REST call using Java. Below is the code I am working with:
JavaScript Code:
import axios from "axios";
const API_URL = "https://jsonplaceholder.typicode.com/posts";
const fetchPosts = async () => {
try {
const response = await axios.get(API_URL);
console.log("Posts:", response.data);
} catch (error) {
console.error("Error fetching posts:", error);
}
};
// Call the function
fetchPosts();
Bundled JavaScript using es bundle
Java Code to Execute the ES Bundled Code:
public static void main( String[] args )
{
String jscode = null;
try {
jscode = new String(Files.readAllBytes(Paths.get("/tmp/main.js")));
} catch (IOException e) {
throw new RuntimeException(e);
}
try (Context context = Context.create()) {
Value value = context.eval("js", jscode);
value.execute();
}
}
pom.xml:
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<graaljs.version>24.1.1</graaljs.version>
<dependency>
<groupId>org.graalvm.polyglot</groupId>
<artifactId>polyglot</artifactId>
<version>${graaljs.version}</version>
</dependency>
<dependency>
<groupId>org.graalvm.polyglot</groupId>
<artifactId>js</artifactId>
<version>${graaljs.version}</version>
<type>pom</type>
</dependency>
<dependency> <!-- all tools we include in Oracle GraalVM -->
<groupId>org.graalvm.polyglot</groupId>
<artifactId>tools</artifactId>
<version>${graaljs.version}</version>
<type>pom</type>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
When I run the above code, I encounter the following error:
Error fetching posts: AxiosError: There is no suitable adapter to dispatch the request since :
adapter xhr is not supported by the environment
adapter http is not available in the build
adapter fetch is not supported by the environment
Could someone please help me figure out how to properly use GraalVM to execute JavaScript code that makes a REST call in Java?
Thank you in advance!