我已尽力描述。如果我对某些事情不够具体,请告诉我,我会进一步解释。
提前致谢!
我正在尝试解析在 POST 请求正文中传递到我的服务器的 JSON 数据。客户端请求是从使用 React 编写的 Web 应用程序发出的,端点位于用 Go 编写的服务器上(下面的代码)。服务器使用结构作为模型正确解析 JSON 数据,但仅在它打印错误“JSON 输入意外结束”以及一个空数组(下面的输出)之后。不过,我只打印一次解析过的 JSON,所以我不知道为什么会这样。此外,如果我多次使用相同的调用跟进 POST,有时行为是正确的。
日志在save函数中的输出为:
[{user: "username", attribute: "playlist", match: true, value: "playlistID"}]
下面的输出是在快速按下保存按钮时创建的,因此多次发出 POST 请求。如果我只按下保存按钮,输出将是:
unexpected end of JSON input
[]
[{username playlist true playlistID}]
[{username playlist true playlistID}]
[{username playlist true playlistID}]
unexpected end of JSON input
[]
[{username playlist true playlistID}]
[{username playlist true playlistID}]
[{username playlist true playlistID}]
[{username playlist true playlistID}]
[{username playlist true playlistID}]
[{username playlist true playlistID}]
[{username playlist true playlistID}]
[{username playlist true playlistID}]
[{username playlist true playlistID}]
[{username playlist true playlistID}]
unexpected end of JSON input
[]
[{username playlist true playlistID}]
[{username playlist true playlistID}]
[{username playlist true playlistID}]
[{username playlist true playlistID}]
save = () => {
var rules = [];
this.state.rules.map((rule, index) => {
var match = rule.matches[rule.state.match];
var value = rule.values[rule.state.value];
var newRule = {
user: this.props.user,
attribute: rule.attribute,
match: match,
value: value.UUID
};
rules.push(newRule);
return newRule;
});
console.log(rules);
Server.saveSmartPlaylist(rules);
};
export function saveSmartPlaylist(data) {
return axios({
method: "POST",
baseURL: "http://localhost:8080",
url: "/smartplaylist",
data: data
}).catch(err => {
console.log(err);
});
}
func Playlists(response http.ResponseWriter, request *http.Request) {
body, err := ioutil.ReadAll(request.Body)
if err != nil {
fmt.Println(err)
}
var rules []rule
err = json.Unmarshal(body, &rules)
if err != nil {
fmt.Println(err)
}
fmt.Println(rules)
rest.PostRequest(response, request, rules)
}
func PostRequest(response http.ResponseWriter, request *http.Request, v interface{}) {
response.Header().Set("Access-Control-Allow-Headers", "Content-Type")
response.Header().Set("Access-Control-Allow-Origin", "*")
response.Header().Set("Access-Control-Allow-Methods", "GET,POST,PUT,DELETE,OPTIONS")
response.Header().Set("Content-Type", "application/json")
enc := json.NewEncoder(response)
enc.SetEscapeHTML(false)
enc.Encode(v)
}
最佳答案
在检查请求方法的 if 中保护已解析 JSON 的实际使用解决了我的问题。
func Playlists(response http.ResponseWriter, request *http.Request) {
var rules []rule
if request.Method == http.MethodPost {
body, err := ioutil.ReadAll(request.Body)
if err != nil {
fmt.Println(err)
}
err = json.Unmarshal(body, &rules)
if err != nil {
fmt.Println(err)
}
var tracks []string
var userID string
for i := 0; i < len(rules); i++ {
rule := rules[i]
ruleTracks := PlaylistMatchValue(rule.User, rule.Match, rule.Value)
tracks = ruleTracks
userID = rule.User
}
updatePlaylist(userID, tracks)
}
rest.PostRequest(response, request, rules)
}
关于json - 从 POST 解析 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47211326/
我有一个字符串input="maybe(thisis|thatwas)some((nice|ugly)(day|night)|(strange(weather|time)))"Ruby中解析该字符串的最佳方法是什么?我的意思是脚本应该能够像这样构建句子:maybethisissomeuglynightmaybethatwassomenicenightmaybethiswassomestrangetime等等,你明白了......我应该一个字符一个字符地读取字符串并构建一个带有堆栈的状态机来存储括号值以供以后计算,还是有更好的方法?也许为此目的准备了一个开箱即用的库?
我主要使用Ruby来执行此操作,但到目前为止我的攻击计划如下:使用gemsrdf、rdf-rdfa和rdf-microdata或mida来解析给定任何URI的数据。我认为最好映射到像schema.org这样的统一模式,例如使用这个yaml文件,它试图描述数据词汇表和opengraph到schema.org之间的转换:#SchemaXtoschema.orgconversion#data-vocabularyDV:name:namestreet-address:streetAddressregion:addressRegionlocality:addressLocalityphoto:i
我正在使用ruby1.9解析以下带有MacRoman字符的csv文件#encoding:ISO-8859-1#csv_parse.csvName,main-dialogue"Marceu","Giveittohimóhe,hiswife."我做了以下解析。require'csv'input_string=File.read("../csv_parse.rb").force_encoding("ISO-8859-1").encode("UTF-8")#=>"Name,main-dialogue\r\n\"Marceu\",\"Giveittohim\x97he,hiswife.\"\
是的,我知道最好使用webmock,但我想知道如何在RSpec中模拟此方法:defmethod_to_testurl=URI.parseurireq=Net::HTTP::Post.newurl.pathres=Net::HTTP.start(url.host,url.port)do|http|http.requestreq,foo:1endresend这是RSpec:let(:uri){'http://example.com'}specify'HTTPcall'dohttp=mock:httpNet::HTTP.stub!(:start).and_yieldhttphttp.shou
我知道您通常应该在Rails中使用新建/创建和编辑/更新之间的链接,但我有一个情况需要其他东西。无论如何我可以实现同样的连接吗?我有一个模型表单,我希望它发布数据(类似于新View如何发布到创建操作)。这是我的表格prohibitedthisjobfrombeingsaved: 最佳答案 使用:url选项。=form_for@job,:url=>company_path,:html=>{:method=>:post/:put} 关于ruby-on-rails-rails:Howtomak
在我的Controller中,我通过以下方式在我的index方法中支持HTML和JSON:respond_todo|format|format.htmlformat.json{renderjson:@user}end在浏览器中拉起它时,它会自然地以HTML呈现。但是,当我对/user资源进行内容类型为application/json的curl调用时(因为它是索引方法),我仍然将HTML作为响应。如何获取JSON作为响应?我还需要说明什么? 最佳答案 您应该将.json附加到请求的url,提供的格式在routes.rb的路径中定义。这
我正在阅读SandiMetz的POODR,并且遇到了一个我不太了解的编码原则。这是代码:classBicycleattr_reader:size,:chain,:tire_sizedefinitialize(args={})@size=args[:size]||1@chain=args[:chain]||2@tire_size=args[:tire_size]||3post_initialize(args)endendclassMountainBike此代码将为其各自的属性输出1,2,3,4,5。我不明白的是查找方法。当一辆山地自行车被实例化时,因为它没有自己的initialize方法
rails中是否有任何规定允许站点的所有AJAXPOST请求在没有authenticity_token的情况下通过?我有一个调用Controller方法的JqueryPOSTajax调用,但我没有在其中放置任何真实性代码,但调用成功。我的ApplicationController确实有'request_forgery_protection'并且我已经改变了config.action_controller.consider_all_requests_local在我的environments/development.rb中为false我还搜索了我的代码以确保我没有重载ajaxSend来发送
简而言之错误:NOTE:Gem::SourceIndex#add_specisdeprecated,useSpecification.add_spec.Itwillberemovedonorafter2011-11-01.Gem::SourceIndex#add_speccalledfrom/opt/local/lib/ruby/site_ruby/1.8/rubygems/source_index.rb:91./opt/local/lib/ruby/gems/1.8/gems/rails-2.3.8/lib/rails/gem_dependency.rb:275:in`==':und
我有一个非常简单的RubyRack服务器,例如:app=Proc.newdo|env|req=Rack::Request.new(env).paramspreq.inspect[200,{'Content-Type'=>'text/plain'},['Somebody']]endRack::Handler::Thin.run(app,:Port=>4001,:threaded=>true)每当我使用JSON对象向服务器发送POSTHTTP请求时:{"session":{"accountId":String,"callId":String,"from":Object,"headers":