Cherrypy and JS, can't find image - javascript

I have a simple Cherrypy script that for now just serves a page. I want the page to be able to display images dynamically. For this I wrote a simple JS script. However when I try to run the page, it can't find the image. The code is run from ~/image_player/test_app.py and the image is at ~/image_player/app/public. See the python code for the static path:
import cherrypy
import os
import sys
class image_player(object):
#cherrypy.expose
def index(self):
return open('app/index.html')
if __name__ == '__main__':
if len(sys.argv) == 2:
port = int(sys.argv[1])
else:
port = 3030
host = '0.0.0.0'
conf = {
'/': {
'tools.sessions.on': True,
'tools.staticdir.root': os.path.abspath(os.getcwd())
},
'/query': {
'request.dispatch': cherrypy.dispatch.MethodDispatcher(),
'tools.response_headers.on': True,
'tools.response_headers.headers': [('Content-Type', 'text/plain')],
},
'/static': {
'tools.staticdir.on': True,
'tools.staticdir.dir': 'app/public'
},
'/js': {
'tools.staticdir.on': True,
'tools.staticdir.dir': 'app/js'
}
}
webapp = image_player()
# Configure server and port
cherrypy.config.update({'server.socket_host': host,
'server.socket_port': port})
cherrypy.quickstart(webapp, '/', conf)
And here's the index.html containing the js:
<!DOCTYPE html>
<html>
<head>
<link href="/static/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
hello
<div id="imageDiv"></div>
<script>
var par = document.getElementById('imageDiv');
var img = document.createElement('img');
img.src = '/LPROFILE.jpg';
par.appendChild(img);
</script>
</body>
</html>
The error I get is GET http://hostname/LPROFILE.jpg 404 (Not Found) I'm clearly missing something simple here but I'm not sure what.

Given the configuration that you showed, the static files are served under the /static path, which means all the files under app/public (relative to the initial directory from which you started the server) are going to be accessible from http://hostname/static/, in the case of LPROFILE.jpg, that should be available in: http://hostname/static/LPROFILE.jpg

It works for me (win x64):
conf = {
'/': {
'tools.sessions.on': True,
'tools.staticdir.root': os.path.abspath(os.getcwd())
},
'/css': {
'tools.staticdir.on': True,
'tools.staticdir.dir': './css'},
'/img': {
'tools.staticdir.on': True,
'tools.staticdir.dir': './img'},
'/js': {
'tools.staticdir.on': True,
'tools.staticdir.dir': './js'},
'global': {
'environment': 'production',
'log.screen': True,
'server.socket_host': '127.0.0.1',
'server.socket_port': 8080,
'engine.autoreload_on': True,
}}
for example:
url(../img/backgr.jpg)

Related

Permanent redirect for www to non-www site using NextJs

I've built a website with Nextjs (using version 12.1.4). For SEO purposes I would like to make a permanent redirect for my www version of the site to my non-www. Normally this could easily be done with nginx or an .htaccess file with apache. However, static websites hosted on Digitalocean are not running apache or nginx so an .htaccess file won’t do. I've read that this should be possible using Nextjs redirects.
I've tried the following 3 redirects:
redirects: async () => [
{
source: '/:path*',
has: [
{
type: 'host',
value: 'www',
},
],
destination: '/:path*',
permanent: true,
},
],
---------------------------------------------------
redirects: async () => [
{
source: '/:path*/',
has: [
{
type: 'host',
value: 'www',
},
],
destination: '/:path*/',
permanent: true,
},
],
------------------------------------------------------
redirects: async () => [
{
source: '/:path*',
has: [{ type: 'host', value: 'https://www.cvtips.nl/' }],
destination: 'https://cvtips.nl/:path*',
permanent: true,
},
],
All of them don't seem to redirect to the non-www version. I don't know if it is relevant, but I do use trailingSlash: true in the config.
Next thing I tried is adding a middleware file. I both tried adding it at the root and calling it middleware.js and inside the pages folder calling it _middleware.js.
This is the code I use for the redirect:
--> https://github.com/vercel/next.js/discussions/33554
import { NextRequest, NextResponse } from 'next/server';
export function middleware(req: NextRequest) {
const host = req.headers.get('host');
const wwwRegex = /^www\./;
// This redirect will only take effect on a production website (on a non-localhost domain)
if (wwwRegex.test(host) && !req.headers.get('host').includes('localhost')) {
const newHost = host.replace(wwwRegex, '');
return NextResponse.redirect(`https://${newHost}${req.nextUrl.pathname}`, 301);
}
return NextResponse.next();
}
Also does not work at all... Doesn't do anything I believe.
How can I redirect a Nextjs website from www to non-www?

In Sveltekit & Vite... How to proxy/hide the folder "api"? Works local but not in Vercel

I'm using sveltekit, when the customers request:
https://example.com/v1/contacts
I would like to be pointing internally to:
https://example.com/api/v1/contacts
*This way I can have a much better cleaner organization in my code.
This is my vite.config.js:
import { sveltekit } from '#sveltejs/kit/vite';
/** #type {import('vite').UserConfig} */
const config = {
plugins: [sveltekit()],
server: {
port: 3001
proxy: {
'/v1': {
target: 'http://127.0.0.1:3001/',
secure: false,
changeOrigin: true,
rewrite: (path) => {
return 'api/' + path;
}
}
}
},
preview: {
port: 3001
}
};
export default config;
It works in localhost, npm run dev, and in localhost when I do npm run preview, but when I upload it to Vercel, it doesn't work. Any ideas?

Webpack Devserver: Open page in browser without typing '.html'

I'm making a plain, static site (HTML/CSS/JS) with Webpack that I intend to eventually deploy to s3. I have my final HTML files exported to the root of my dist folder like, index.html, foo.html, bar.html.
When I go to localhost:9000, my index loads as expected. For foo and bar I have to type the file extension like /foo.html and /bar.html for those pages to load. Is there a setting that I'm missing that will allow me to simply type /foo and /bar in the browser and have the intended pages load?
One way I found for individual pages, is to specify a proxy using devServer.proxy. For /foo and /bar, this would look like that:
const path = require("path");
module.exports = {
...
devServer: {
static: {
directory: path.resolve(__dirname, 'dist')
},
port: 3000,
open: false,
hot: true,
proxy: {
'/foo': {
target: 'http://localhost:3000/foo.html',
pathRewrite: { '^/foo': '' }
},
'/bar': {
target: 'http://localhost:3000/bar.html',
pathRewrite: { '^/bar': '' }
}
}
}
}
Check the DevServer documentation for more options.
In addition to Nikolai's answer, in case you need your local dev server to serve urls w/o extensions in router history mode, just use the following:
historyApiFallback: {
rewrites: [
{ from: /^\/$/, to: '/views/landing.html' },
{ from: /^\/subpage/, to: '/views/subpage.html' },
{ from: /./, to: '/views/404.html' },
],
},
Source: https://webpack.js.org/configuration/dev-server/#devserverhistoryapifallback

Ignore certain .js files with webpack dev server running --hot

I have the need to import some javascript files as pure text with webpack.
All the files have a specific extension say: .mytype.js.
I have created a loader for these files using:
module.loaders = [{
test: /\.mytype.js?$/,
exclude: /(node_modules|bower_components|public\/)/,
loader: "mytype-loader"
}, ....]
I have regstered an alias to resolve my own loader
resolveLoader : {
alias : {
'mytype-loader' : path.resolve(__dirname, 'myloader.js')
}
}
At the moment myloader.js looks like this:
module.exports = source => {
console.log(source)
return(source)
}
For my dev server I have the following setup:
devServer: {
watchOptions : {
// I THOUGHT THIS WOULD STOP HOTLOAD CODE BEING ADDED??!
ignored : path.resolve(__dirname, 'mytypeFiles')
},
contentBase: CONTENT_BASE,
noInfo: true,
hot: true,
inline: true,
port: PORT,
headers : { 'Access-Control-Allow-Origin' : 'http://localhost:8888'},
host: HOST
},
All of my files with extension .mytype.js are in the mytypeFiles directory. The problem is that when I run this I get the following output from the loaders console.log
'use-strict';
function run(args, resources, meta) {
// a bunch of my code
}
;
var _temp = function () {
if (typeof __REACT_HOT_LOADER__ === 'undefined') {
return;
}
__REACT_HOT_LOADER__.register(run, 'run', 'D:/manatee-latest/manatee/src/bandicoot/resource-api/bandicoot-functions/run.bandicoot.js');
}();
However use-strict; and everything after the first function definition (which is mine) has been attached. How do I stop this hot loader code from being pre & post-fixed to my source?
Thanks in advance!

Hapi.js views not seeing local scripts

I'm currently working on an app with a server that uses Hapi, and I am running into a problem whenever I try to load a .jade file. Here is the current code for my index.js file:
var Hapi = require('hapi');
var internals = {};
internals.main = function() {
var options = {
views: {
engines: { jade: 'jade' },
path: '../app',
compileOptions: {
pretty: true
}
}
};
this._server = new Hapi.createServer('localhost', 8000, options);
this._server.route({
method: 'GET',
path: '/',
handler: function(request, reply) {
reply.view('index')
}
});
// Start server.
this._server.start()
};
internals.main();
The file has a series of local scripts and CSS files that are in the app directory, but when the page index.jade is loaded, it does not see those local files. Is there something I need to add/modify in my options, or is this location of local scripts and style files a problem with jade compilation using Hapi?
I was looking for a similar solution, while trying to setup a single page application with angular.js and hapi.js
I have found that adding the configuration below to your server routes will help to make CSS, JS, ... files in '/public' directory visible to the application.
server.route({
method: "GET",
path: "/public/{path*}",
handler: {
directory: {
path: "./public",
listing: false,
index: false
}
}
});
Hope it helps.

Categories