gpt4 book ai didi

javascript - 发送 JSON 到服务器

转载 作者:行者123 更新时间:2023-12-02 22:33:53 25 4
gpt4 key购买 nike

我正在尝试通过 ajax 请求将 json 发送到我的服务器。这是关于在 jupyter lab 中集成的一个 Web 应用程序,我想将文件保存在云中而不是保存在本地,因此我需要将 json 发送到服务器,然后将其保存为 json 文件。

我在客户端尝试了 ajax POST 请求。

          $.ajax({  
url: '/discoverjson',
data: jsonString,
contentType: 'application/json;charset=UTF-8',
type: 'POST',
dataType: "json",
success: function(response) {
console.log(response)
},
error: function(error) {
console.log(error)
}
});

我正在 Tornado 网络服务器中请求响应,如下所示:

class JSONHandler(tornado.web.RequestHandler):
def get(self):
if self.request.headers.get("Content-Type", "").startswith("/discoverjson"):
self.json_args = json.loads(self.request.body)
self.write(json_args)
else:
self.write('JSON Empty!')
self.json_args = None

如果我访问http://localhost:9999/discoverjson我得到'JSON Empty!' 。问题是如果我尝试发送我收到的 json 403 (Forbidden) .

我没有重要的背景,也许这不是最好的方法。

有什么想法吗?

编辑

我更改了此语法 self.request.headers.get("Content-Type", "").startswith("/discoverjson")self.request.headers.get("Content-Type", "")但访问仍然被禁止。

客户端控制台: 403 (Forbidden)

服务器端控制台:

[W 11:14:38.263 LabApp] 403 POST /discoverjson (172.21.0.1): '_xsrf' argument missing from POST
[W 11:14:38.263 LabApp] 403 POST /discoverjson (172.21.0.1) 0.92ms referer=http://localhost:9999/discover/index.html?

最佳答案

问题似乎是你的 if 语句

if self.request.headers.get("Content-Type", "").startswith("/discoverjson")

让我们稍微分解一下

self.request.headers.get("Content-Type","")

这将返回 application/json;charset=UTF-8 因为这是您在 Javascript 中设置的值。

所以它永远不会以 /discoverjson 开头

关于javascript - 发送 JSON 到服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58799309/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com