#how to connect js script to html using serve

1 messages · Page 1 of 1 (latest)

lunar burrow
#

i want to connect script.js in index.html, but i get an error Uncaught SyntaxError: Unexpected token '<'. what should i do?

safe flax
#

you are returning html for /script.js path

lunar burrow
#

but im not

#

in script.js only console.log

safe flax
#

your code returns index.html file for every path

#

that's why when browser tries to load script.js it gets back html

lunar burrow
#

yea, i tried to this Bun.file('./public') but it was a big mistake

#

there was too many errors

safe flax
#

Bun.file() only read single file at provided path

lunar burrow
#

yea i got it

#

so what should i do? just type public?

safe flax
#

you need some kind of routing code that will return proper file for given path

lunar burrow
#

what do u mean

#

im noob...

safe flax
#

for example ```js
export default {
fetch(req) {
const url = new URL(req.url);
if (url.pathname === '/') return new Response(Bun.file('./public/index.html'));
if (url.pathname === '/script.js') return new Response(Bun.file('./public/script.js'));
},
}

#

you can write code that will automate all of this for all files in public folder

#

or use existing libraries/frameworks that do it

lunar burrow
#

oh god that's really working

#

but how

#

URL { href: "http://localhost:3012/favicon.ico", origin: "http://localhost:3012", protocol: "http:", username: "", password: "", host: "localhost:3012", hostname: "localhost", port: "3012", pathname: "/favicon.ico", hash: "", search: "", searchParams: {}, toJSON: [Function: toJSON], toString: [Function: toString] }

#

this is url

#

how is pathname changing?

safe flax
#

it's part of whole url

#

if your browser makes request to localhost:3012/hello then path will be /hello

lunar burrow
#

so when browser in index.html reached to <script> tag, it automatically changes pathname?

safe flax
#

yeah

#

it makes a http request to localhost:3012/script.js

lunar burrow
#

okey i got it

#

thank you very much!

#

<3

shut silo
#

Hi, how can i serve a file with the bun.serve? When i use bun.file(‘index.js’) and it’s retuen file but this code can find directory in new Response(). Where is the problem?