简体   繁体   English

编辑:无法使用 Fetch API 向 Express 服务器发送 POST 请求,不断收到 JSON.parse 错误

[英]EDITED: Can't send POST request to Express server with Fetch API, keep getting JSON.parse error

I'm new to JavaScript, and am learning to develop with an Express server on Glitch.com.我是 JavaScript 新手,正在学习使用 Glitch.com 上的 Express 服务器进行开发。 I am running into issues with my Fetch API POST request, where it keeps returning a JSON.parse error when I try to send it a JSON object.我的 Fetch API POST 请求遇到了问题,当我尝试向它发送 JSON 对象时,它不断返回 JSON.parse 错误。

SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data

I plan on using the JSON object to take in input from an HTML form, and I have that data saved in string variables but cannot use it.我计划使用 JSON 对象接收来自 HTML 表单的输入,并且我将该数据保存在字符串变量中但无法使用它。 When I test JSON.stringify and JSON.parse in the console, it logs it as当我在控制台中测试 JSON.stringify 和 JSON.parse 时,它​​将其记录为

Object { some: 1 }

I am also not sure where I should be directing the URL of the Fetch API, though the Express code is saved in a folder in Glitch called "server/ex.js".我也不确定应该将 Fetch API 的 URL 指向哪里,尽管 Express 代码保存在 Glitch 中名为“server/ex.js”的文件夹中。 Thank you in advance!先感谢您!

UPDATE So it looks like I'm getting errors with my Express server, when I check the response status code it's 404. How do I find the right URL?更新所以看起来我的 Express 服务器出现错误,当我检查响应状态代码时,它是 404。如何找到正确的 URL?

try this code:试试这个代码:

var payload = {
    a: 1,
    b: 2
};

var data = new FormData();
data.append( "json", JSON.stringify( payload ) );

fetch("/echo/json/",
{
    method: "POST",
    body: data
})
.then(function(res){ return res.json(); })
.then(function(data){ alert( JSON.stringify( data ) ) })

This code above is in: Fetch: POST json data上面这段代码在: Fetch: POST json data

If you started a node project, you will want to edit the server.js file to include the following codes:如果您启动了一个节点项目,您将需要编辑server.js文件以包含以下代码:

app.post('/server/ex.js',function(req,res){
  res.send(JSON.stringify({
    'hello':'world'
  }))
})

then the fetch request in client.js should return the json object那么client.js的 fetch 请求应该返回 json 对象

edit1) sorry, just realised it was a post request, not a get request编辑1)抱歉,刚刚意识到这是一个发布请求,而不是一个获取请求

edit2) in order to parse the json object you sent {some:1} , you will need bodyparser package . edit2) 为了解析您发送的 json 对象{some:1} ,您将需要bodyparser package

edit after seeing server.js :看到server.js后编辑:

you will need the following for server.js at the very top if it does not already:如果server.js还没有的话,你将需要它在最顶部的以下内容:

var express = require('express')
var app = express()

in addition, it will need the code snippit above somewhere later.此外,稍后它将需要上面的代码片段。

I am not too sure where you are getting the next() function from, though.不过,我不太确定您从哪里获得next()函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM