如何在Golang中使用JavaScript(V8go、Otto)中的Fetch?

huangapple go评论93阅读模式
英文:

How to use Fetch in JavaScript (V8go, Otto) in Golang?

问题

我正在尝试在Golang函数中运行JavaScript,并使用fetch在JavaScript上下文中通过API获取JSON。

我在Otto中尝试了以下代码:

import "github.com/robertkrimen/otto"
vm := otto.New()
vm.Run(`
function tryfunc() {
    console.log("Started");
    fetch('https://www.example.com/APIendpoint');
    console.log("Success");
}
tryfunc();
`)

Otto非常简单易用,但似乎它是一个事件总线,并不支持fetch。

我现在正在尝试使用v8go,以下是代码示例:

import v8 "rogchap.com/v8go"
ctx := v8.NewContext()
ctx.RunScript(`fetch("https://www.example.com/APIendpoint"), ""`)

但它需要另一个参数。文档非常不清楚,很难理解如何运行最简单的JS脚本。

有人可以帮忙吗?

英文:

I am trying to run JavaScript inside of a Golang function, and use fetch to fetch JSON via APIs in the Javascript context.

I tried it in Otto with the following code:

import "github.com/robertkrimen/otto"
	vm := otto.New()
	vm.Run(`
	function tryfunc() {
		console.log("Started");
		fetch('https://www.example.com/APIendpoint');
		console.log("Success");
	}
	tryfunc();
	`)

Otto is very simple to use, but looks like Otto is an event bus and does not manage fetch.

I am now trying with v8go with the following code:

import v8 "rogchap.com/v8go"
ctx := v8.NewContext()
ctx.RunScript(`fetch("https://www.example.com/APIendpoint"), ""`)

but it requires another argument. The documentation is very unclear and is difficult to understand how to run even the simplest JS script.

Can someone help?

答案1

得分: 1

Otto和v8实现了ECMAScript,截至当前的13.0版本,不需要内置函数fetch(参见:https://262.ecma-international.org/13.0/#sec-function-properties-of-the-global-object),这个函数由Web浏览器实现。

我认为第二个参数只是一个文件名,用于前缀调试输出(例如:foo.js:14: undefined bar),这在解释器中非常常见。

我怀疑你的脚本已经运行过了,如果你打印出RunScript的输出(你忽略了返回值,一个JavaScript值和一个错误),那应该会有一个"undefined function fetch"和值nil。请注意,v8go文档中有一个实现fetch的示例。

英文:

Otto and v8 implements ECMAScript and as of current 13.0 version doesn't require a builtin function fetch (See: https://262.ecma-international.org/13.0/#sec-function-properties-of-the-global-object), this function is implemented by web browsers.

I believe the second argument is simply a file name to prefix debug output (eg: foo.js:14: undefined bar), that's very usual in interpreters.

I suspect your script did ran, if you print out the output from RunScript (you're ignore both return values, a JavaScript value and an error), that should have an "undefined function fetch" and value nil. FYI there is an example for implementing fetch in v8go documentation.

huangapple
  • 本文由 发表于 2022年7月5日 22:10:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/72870879.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定