-1

I'm new to JavaScript, and am learning to develop with an Express server on Glitch.com. 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.

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. When I test JSON.stringify and JSON.parse in the console, it logs it as

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". 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?

bzrkly
  • 1
  • 2
  • What exactly does the response body look like? (You can see it in the "Network" tab in your browser developer tools.) The error is from the client-side code that tries to treat the server response as JSON. – Pointy Mar 10 '18 at 15:26
  • @Pointy Oh! It says: "Cannot POST /server/ex.js" does this mean it's a problem with Express? Thank you so much for the quick response btw – bzrkly Mar 10 '18 at 15:27
  • Right; it's a bad URL or there's no handler for a POST or something, and then your client-side code attempts to parse that error message as JSON. – Pointy Mar 10 '18 at 15:28
  • @Pointy sorry hit enter too quickly, it says Cannot POST /server/ex.js – bzrkly Mar 10 '18 at 15:28
  • Thanks for the heads up, that's useful to know. I'm using some example code, and I'm not sure if it has a POST handler or not. I'm thinking of testing out body-parser, thank you for the help! – bzrkly Mar 10 '18 at 15:36
  • would be great to see the guide that you are following. my guess is 1) you are suppose to `fetch('http://HOSTNAME:PORT/server/ex.js')` or you are suppose to also write the post request handlers server side – pandamakes Mar 10 '18 at 16:02
  • @pandamakes now it kind of looks like Frankenstein code haha. It's hosted in Glitch, which gives you a custom URL for every project in the format "https://random-word.glitch.me". Just tried your suggestion with "https://random-word.glitch.me:3000/server/ex.js", and it's giving me "TypeError: NetworkError when attempting to fetch resource"? – bzrkly Mar 10 '18 at 16:06
  • true, you did mention you want to develop an express server. Is this your backend code? i.e., do you have something like `const express = require('express')` etc? edit: probably easier also, if you can share any other codes + files in your current project – pandamakes Mar 10 '18 at 16:12

2 Answers2

1

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

Mateus Gabi
  • 99
  • 1
  • 2
  • Thanks Mateus, I tried it and it still gave me the error. In the comments above I found out that it's actually a problem with my Express server - I'm getting a 404 status code when I try to POST. Do you have any tips? – bzrkly Mar 10 '18 at 16:01
  • @bzrkly can you share a [Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve) – Mateus Gabi Mar 10 '18 at 16:15
  • Yes, here's the Express code, the sample I was looking at also used Next.js but I'm having trouble understanding it. Sorry for the newbieness on here & thanks!: app.post('/submit', async (req, res) => { console.log(req); res.sendStatus(200); }); const nextApp = next({ dev: process.env.NODE_ENV !== 'production' }); const nextHandler = nextApp.getRequestHandler(); app.get('*', (req, res) => nextHandler(req, res)); nextApp.prepare().then(() => { app.listen(3000, (error) => { if (error) { throw error; } console.log(`listening on 3000`); }); }); – bzrkly Mar 10 '18 at 16:21
  • @bzrkly ok, I'm writing a simple example https://github.com/MateusGabi/Express-JS-Simple-Example – Mateus Gabi Mar 10 '18 at 16:25
  • Thank you so much! I really appreciate the help :) – bzrkly Mar 10 '18 at 16:29
0

If you started a node project, you will want to edit the server.js file to include the following codes:

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

edit1) sorry, just realised it was a post request, not a get request

edit2) in order to parse the json object you sent {some:1}, you will need bodyparser package.

edit after seeing server.js:

you will need the following for server.js at the very top if it does not already:

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.

pandamakes
  • 571
  • 3
  • 8