72582

Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0 while acess static fi

Question:

Hi i am developing small application using react create app with node in thatis application i want to acess static file in node i use like this

app.get('*', (req, res) => { res.sendFile(path.resolve(__dirname, "/", 'build', 'index.html')); });

but i am getting getting error

Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0

Answer1:

This is because you are serving the same file for every request - also for the scripts required by the original HTML page. The browser request script, it gets HTML and the parser fails on < of <doctype> or <html>.

You can see in the Network tab of your browser's developer console all of the requests that your browser is making - I can bet that you're requesting something like script.js and instead of JavaScript contents you get the HTML contents of your index.html file.

It seems that you're using Express. Use express.static to serve static files instead of res.sendFile()

Since it seems that you have every static file in build, use something like this:

const path = require('path'); const express = require('express'); const app = express(); const dir = path.join(__dirname, 'build'); app.use(express.static(dir)); app.listen(3000, function () { console.log('Listening on http://localhost:3000/'); });

This is the entire program that you need. Of course you can change the port number.

It will serve your index.html correctly but it will also serve all of the other assets like images, client-side scripts required with <script>, CSS files etc. plus also other HTML files if there are any.

If you don't want to use Express then see this answer for more options of serving files:

<ul><li><a href="https://stackoverflow.com/questions/5823722/how-to-serve-an-image-using-nodejs/40899767#40899767" rel="nofollow">How to serve an image using nodejs</a></li> </ul>

Recommend

  • Apache graceful restart - Does it affect current PHP script execution
  • Why does Perl's IO::Socket on Windows complain about “Resource Not Available” after 64 connecti
  • Open a Configuration Profile through app
  • How do I provide inline input to an IPython (notebook) shell command?
  • Qpython unicode strings
  • Run python script inside powershell script
  • The C Programming Language K&R exercise 1- 9
  • Property 'catch' does not exist on type 'PromiseLike
  • KoGrid JSON Dynamic widgets, with nested server calls
  • Cleave.js Phone CA
  • I have a modal that opens a second modal and cannot close the first modal if open then close the sec
  • jQuery file download plugin
  • Why is my req.body always empty on POST?
  • Understanding Intl.DateTimeFormat as a JavaScript object
  • IDX10503: Signature validation failed
  • oauth2client.client.HttpAccessTokenRefreshError: invalid_grant: Invalid JWT
  • Syntax error near unexpected token 'elif'
  • read values from form post in jquery or javascript
  • Connecting bluetooth device to windows phone 8 application
  • Best practice to eliminate magic numbers within a member function
  • CXF JAXB JAXBEncoderDecoder unmarshalling error : unexpected element when having qualified elements
  • How to use jQuery's $.post() method with async/await and typescript
  • Unexpected token ILLEGAL while running node.js mocha test
  • Blackberry - Custom EditField Cursor
  • Play WS (2.2.1): post/put large request
  • Body moving without any force applied? (Box2d)
  • Different response to non-authenticated users and AJAX calls
  • Why HTML5 Canvas with a larger size stretch a drawn line?
  • Warning: Can't call setState (or forceUpdate) on an unmounted component
  • Unit Testing MVC Web Application in Visual Studio and Problem with QTAgent
  • Hits per day in Google Big Query
  • FormattedException instead of throw new Exception(string.Format(…)) in .NET
  • Android Google Maps API OnLocationChanged only called once
  • Linking SubReports Without LinkChild/LinkMaster
  • Is it possible to post an object from jquery to bottle.py?
  • XCode 8, some methods disappeared ? ex: layoutAttributesClass() -> AnyClass
  • costura.fody for a dll that references another dll
  • Observable and ngFor in Angular 2
  • UserPrincipal.Current returns apppool on IIS
  • java string with new operator and a literal