Register a SA Forums Account here!
JOINING THE SA FORUMS WILL REMOVE THIS BIG AD, THE ANNOYING UNDERLINED ADS, AND STUPID INTERSTITIAL ADS!!!

You can: log in, read the tech support FAQ, or request your lost password. This dumb message (and those ads) will appear on every screen until you register! Get rid of this crap by registering your own SA Forums Account and joining roughly 150,000 Goons, for the one-time price of $9.95! We charge money because it costs us money per month for bills, and since we don't believe in showing ads to our users, we try to make the money back through forum registrations.
 
  • Post
  • Reply
smackfu
Jun 7, 2004

If I have a POST request that seems to follow the rules for being a simple request and doesn’t trigger a CORS OPTIONS preflight, why would it still be blocked by CORS in chrome? It seems like it still wants an Access-Control-Allow-Origin header from the server, but I thought the whole point of “simple requests” was that they are backward compatible with services that predate CORS.

I’m almost surely going to have to wrap this old service in a CORS supporting wrapper, so this is mainly just curiosity.

Adbot
ADBOT LOVES YOU

TheFluff
Dec 13, 2006

FRIENDS, LISTEN TO ME
I AM A SEAGULL
OF WEALTH AND TASTE

smackfu posted:

If I have a POST request that seems to follow the rules for being a simple request and doesn’t trigger a CORS OPTIONS preflight, why would it still be blocked by CORS in chrome? It seems like it still wants an Access-Control-Allow-Origin header from the server, but I thought the whole point of “simple requests” was that they are backward compatible with services that predate CORS.

I’m almost surely going to have to wrap this old service in a CORS supporting wrapper, so this is mainly just curiosity.

The same origin policy for Javascript is almost as old as Javascript itself and as such even predates XMLHttpRequest and the whole Ajax thing. It has AFAIK never been possible to do a Javascript HTTP request to a different origin without the server including an access-control-allow-origin header in the response (barring some weird and long deprecated old hacks). Like, try opening a console on any website and typing in "await fetch('https://example.com');" and you'll get a CORS error. Before CORS was a thing, you simply couldn't make XHR requests to other origins, it just wasn't possible. If you really wanted that sort of thing you had to do proxying or stupid hacks like creating an invisible form element and trigger the submission with JS, because cross origin form submission was OK. Simple requests are not preflighted because they only allow things non-Javascript content can already do (see e.g. ad tracking with "tracking pixels", <img> elements that load a 1x1 pixel transparent GIF in order to send tracking data to the advertiser via query string parameters). Note that if you try to do a simple cross-origin request without CORS, the browser doesn't actually block the request from happening - if it's a POST it actually does send the data to the server. Instead, if the response doesn't have the appropriate access-control-allow-origin header the CORS error is triggered and prevents the Javascript code from knowing anything about what happened to the request.

TheFluff fucked around with this message at 15:54 on Jan 29, 2021

MrMoo
Sep 14, 2000

Is the Content-Type one of the form submission ones? Try doing the same POST with just a vanilla <form></form>.

smackfu
Jun 7, 2004

Thanks, that makes it clearer.

I spent way too long banging my head against this because I thought an existing system was making the request I wanted to make, but it turns out they were running the request from an iframe so it wasn’t cross origin.

Nolgthorn
Jan 30, 2001

The pendulum of the mind alternates between sense and nonsense
Trying to write my own unit test runner.

But I'm having trouble figuring out in node how to do a few things, mainly because all the existing test frameworks just contain so much code and dependencies I'm not sure where I am supposed to be looking. For starters I'm having trouble figuring out how I go about running all the test files pragmatically.

I can look through all the directories and find `.test.js` files. Once I know where they all are I run all of the test files, placing the tests into a buffer. Then I start making my way through the tests but I still don't know how I'm making these files run. I just use `require()`?

That's a good place to start.

How do I inject my `describe` and `it` methods into each of the files before running them?

Nolgthorn
Jan 30, 2001

The pendulum of the mind alternates between sense and nonsense
Wait a second, do I just set global methods in my test runner surely I'm not supposed to.

necrotic
Aug 2, 2005
I owe my brother big time for this!
Yeah, you'd put them on global. That's how other runners that automatically provide those functions would do it.

Nolgthorn
Jan 30, 2001

The pendulum of the mind alternates between sense and nonsense
Dear god it works. I published it.

https://www.npmjs.com/package/kequtest

Nolgthorn
Jan 30, 2001

The pendulum of the mind alternates between sense and nonsense
I've added hooks before, beforeEach, etc.. having fun with this now. Mocks and spies are libs that can be required at the top of tests that need them. I don't think it really fits the spirit of a super simple test library to include those things anyway. Gonna leave it alone unless I can think of anything else it needs.

Empress Brosephine
Mar 31, 2012

by Jeffrey of YOSPOS
Hey all

I want to try building my personal site in React but based on Express. I’m guessing in this case most people just use a Express framework to serve up as a API serving json data to the React side? There’s no real “idiots guide” to this that I’ve found online, and I feel pretty comfortable with Express so far that I’d like to use it for more than just serving up PUG templates (although I really enjoy PUG)

Thanks for the help / direction

barkbell
Apr 14, 2006

woof
I would suggest running through the official react tutorial. I would even recommend using cra or next.js and doing those tutorials to begin with.
https://reactjs.org/tutorial/tutorial.html
https://create-react-app.dev/docs/getting-started
https://nextjs.org/learn/basics/create-nextjs-app

You are right that it is common that the node/express is set up as an API serving data via JSON over the web.

The react part comes into play when a user will have the html, js, css etc files loaded in their browser (those could have been served up by the express server as well or a completely different server). The js files running in the users browser will access the web resources served up by the express server via something liek the fetch api or maybe axios.
https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API
https://github.com/axios/axios

If you google react and nodejs I'm sure there are lots of articles of people walking through the basic process. I hope that helped.

Empress Brosephine
Mar 31, 2012

by Jeffrey of YOSPOS
it does, thanks so much I’ll check that out.

I have a little experience with NextJS. How much different from Express its he server language for NextJS?

barkbell
Apr 14, 2006

woof
the syntax is similar. the tutorial i linked above for it only takes an hour to run through

Empress Brosephine
Mar 31, 2012

by Jeffrey of YOSPOS
Sweet ill do that then, thank you

Roadie
Jun 30, 2013
Next.js API routes use the same interface as Express and are Connect-compatible for middleware, but the routes for actual pages are more complicated because it's injecting various stuff to handle rehydration of server-side-rendered pages (and ideally you don't have to manually mess with that part of things). In practice you can treat it like two separate servers that happen to be run by the process for convenience's sake.

Empress Brosephine
Mar 31, 2012

by Jeffrey of YOSPOS
Seems not too bad, I’ll take a look. I really like Express and I wish there was a way to incorporate a version of REACT into Pugs templating, which I far enjoy writing more than HTML

Thanks goons

The Fool
Oct 16, 2003


I write jsx for simple pages because I don’t want to deal with regular HTML or css ever again

OtspIII
Sep 22, 2002

Is there an accepted Best Way for a small site to handle account management/password security/etc? I could definitely figure out how to store account info in a DB and encrypt passwords by myself, but I'm admittedly pretty new to web dev and feel like there must be better solutions out there. Googling for an answer has the issue of finding lots of examples of how I *could* set things up, but I'm not sure which way I *should*. Do people hand-roll their own accounts, or are there good packages I could use, or is it pretty standard to use a third party service?

I'm not yet taking credit card info from people, but likely will in the near to mid future, if that changes things.

For context, I have a fake D&D gambling game running with a React frontend and a ExpressJS backend on AWS, and it got noticed on Reddit (and, by extension, 4chan) before I was entirely ready for it. Chat is a big component of it, and post-4chan things have gotten a little. . .racist, transphobic, and rapey. I hadn't added an accounts system yet, so moderation is proving to be a losing battle and now I'm scrambling to get accounts added ASAP

The Fool
Oct 16, 2003


Check out Auth0

You could also just use passportjs or similar to offload your entire user management to google or Facebook

Impotence
Nov 8, 2010
Lipstick Apathy
to add, if you don't verify at least email/have a captcha/etc, things will continue to be that way, creating an account that doesn't require anything past a single request to an endpoint doesn't add any friction whatsoever

Empress Brosephine
Mar 31, 2012

by Jeffrey of YOSPOS
I use passportjs and bcrypt with express for authentication

OtspIII
Sep 22, 2002

Auth0 looks really useful, but jesus christ does it get scary if you pass 7k monthly users. Straight from free to $228/month, going up pretty quickly from there. With zero advertising we've been hitting spikes of 500 simultaneous users, so I think it's pretty likely we'd end up triggering that. I'm probably going to add some paid vanity features to help fund server costs and so on, but I really doubt conversion rates are going to be anywhere high enough to support that.

The Fool posted:

You could also just use passportjs or similar to offload your entire user management to google or Facebook

Can passportjs be used in a more traditional manner, as well? Or is it purely for connecting to other services?

Biowarfare posted:

to add, if you don't verify at least email/have a captcha/etc, things will continue to be that way, creating an account that doesn't require anything past a single request to an endpoint doesn't add any friction whatsoever

Oh yeah, for sure. These are some of the things I'm hoping packages/etc will give me a hand with

Impotence
Nov 8, 2010
Lipstick Apathy
there's a strategy for it but it looks quite old https://github.com/jaredhanson/passport-local

worms butthole guy
Jan 29, 2021

by Fluffdaddy
I use the local strategy connected to Postgres and it seems to work okay although not sure how it would go with huge accounts like that

roomforthetuna
Mar 22, 2005

I don't need to know anything about virii! My CUSTOM PROGRAM keeps me protected! It's not like they'll try to come in through the Internet or something!

OtspIII posted:

For context, I have a fake D&D gambling game running with a React frontend and a ExpressJS backend on AWS, and it got noticed on Reddit (and, by extension, 4chan) before I was entirely ready for it. Chat is a big component of it, [...]
People saying "if you can just create a new account effortlessly then moderation is still impossible" are right; one thing you might consider, since it's a game context, depending on the nature of your game, is requiring that a certain amount of success in the game be achieved before write access to the chat is granted.

People can still potentially game that kind of a system by making a bot, but short of only granting access after taking payment it's a pretty good method. The other downside is sometimes people will whine about it, if the chat is the main reason they want to play your thing.

Empress Brosephine
Mar 31, 2012

by Jeffrey of YOSPOS
That's a cool website btw

Happy Thread
Jul 10, 2005

by Fluffdaddy
Plaster Town Cop
I just switched editors from JetBrains Webstorm to VSCode to try it out. Unfortunately, my code library was written using Webstorm's built-in formatter for JavaScript code. Apparently this formatter is unique to Webstorm with some reasonable defaults, but it is actually quite configurable. In fact, I'm having trouble matching the settings I chose with any other formatter.

What I want is to avoid having to make a code commit with a huge changelog just because I couldn't get any VSCode extensions to format without making a ton of changes that Webstorm's formatter wouldn't have.

What is the most configurable JavaScript formatter I can use, providing enough settings to maybe give me a shot at matching the style that I already have? Looking at Beautify it seems to have barely a dozen settings that apply to JavaScript, compared to hundreds for Webstorm.

teen phone cutie
Jun 18, 2012

last year i rewrote something awful from scratch because i hate myself
I'd say https://prettier.io/ is the most common one, and has good VSCode support.

I usually highlight selections and format on a keybinding, but also have prettier in my project dependencies and format on precommit. I'd say you're better off just merging a monster PR to use a standardized formatting library

Away all Goats
Jul 5, 2005

Goose's rebellion

Total JS newbie here. I am trying to build a BMR calculator that can provide the BMR given either imperial or metric input. For some reason the imperial works fine, but the metric input returns NaN despite having nearly identical code.

Could some fresh eyes please look at this and tell me what I'm doing wrong?
code:
var system = document.getElementById("system").value;

function SystemUsage() {
    if (system == "imperial")
        CalculateImperialBMR();
    else if (system == "metric")
        CalculateMetricBMR();
}
function CalculateMetricBMR() {    
    var metricWeight = parseFloat(document.getElementById("weightKG").value);
    var metricHeight = parseFloat(document.getElementById("heightCM").value);
    var age = parseFloat(document.getElementById("age").value);
    var gender = document.getElementById("gender").value;
    var exerciselevel = document.getElementById("exerciselevel").value;
    var MaintenanceCalories = 0;

    // Using Harris-Benedit equation revised by Miifflin and St Jeor(1990):
    // Men	 BMR = (10 × weight in kg) + (6.25 × height in cm) - (5 × age in years) + 5
    // Women BMR = (10 × weight in kg) + (6.25 × height in cm) - (5 × age in years) - 161
    if (gender == "male") {
        var totalWeight = 10 * metricWeight;
        var totalHeight = 6.25 * metricHeight;
        var userAge = 5 * age;
        var result = totalWeight + totalHeight - userAge + 5;
    }

    else if (gender == "female") {
        var totalWeight = 10 * metricWeight;
        var totalHeight = 6.25 * metricHeight;
        var userAge = 5 * age;
        var result = totalWeight + totalHeight - userAge - 161;
    }

    switch (exerciselevel) {
        case "low":
            MaintenanceCalories = result * 1.53;
            break;
        case "medium":
            MaintenanceCalories = result * 1.76;
            break;
        case "high":
            MaintenanceCalories = result * 2.25;
            break;
        default: "medium";
    }

    document.getElementById("bmrResult").innerHTML = 'Your BMR is: ' + result.toFixed(2) + '<p> Your Maintenance Calories are: ' + MaintenanceCalories.toFixed(2)
} 

function CalculateImperialBMR() {

    var gender = document.getElementById("gender").value;
    var imperialHeight = (parseFloat(document.getElementById("heightFeet").value) * 12) + parseFloat(document.getElementById("heightInches").value) * 2.54;
    var imperialWeight = parseFloat(document.getElementById("weightPounds").value) / 2.205;
    var age = parseFloat(document.getElementById("age").value);
    var exerciselevel = document.getElementById("exerciselevel").value;
    var MaintenanceCalories = 0;  

    // Using Harris-Benedit equation revised by Miifflin and St Jeor(1990):
    // Men	 BMR = (10 × weight in kg) + (6.25 × height in cm) - (5 × age in years) + 5
    // Women BMR = (10 × weight in kg) + (6.25 × height in cm) - (5 × age in years) - 161
    if (gender == "male") {
        var totalWeight = 10 * imperialWeight;
        var totalHeight = 6.25 * imperialHeight;
        var userAge = 5 * age;
        var result = totalWeight + totalHeight - userAge + 5;        
    }
    else if (gender == "female") {
        var totalWeight = 10 * imperialWeight;
        var totalHeight = 6.25 * imperialHeight;
        var userAge = 5 * age;
        var result = totalWeight + totalHeight - userAge - 161;        
    }

    switch (exerciselevel) {
        case "low":
            MaintenanceCalories = result * 1.53;
            break;
        case "medium":
            MaintenanceCalories = result * 1.76;
            break;
        case "high":
            MaintenanceCalories = result * 2.25;
            break;
        default: "medium";
    }

    document.getElementById("bmrResult").innerHTML = 'Your BMR is: ' + result.toFixed(2) + '<p> Your Maintenance Calories are: ' + MaintenanceCalories.toFixed(2)
} 
is the scope of the variables interfering with each other?

Away all Goats fucked around with this message at 05:20 on Feb 5, 2021

Happy Thread
Jul 10, 2005

by Fluffdaddy
Plaster Town Cop
So there's no way to avoid a giant history-ruining diff when you switch IDEs?

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

Away all Goats posted:

Total JS newbie here. I am trying to build a BMR calculator that can provide the BMR given either imperial or metric input. For some reason the imperial works fine, but the metric input returns NaN despite having nearly identical code.

Could some fresh eyes please look at this and tell me what I'm doing wrong?
code:
var system = document.getElementById("system").value;

...
} 
is the scope of the variables interfering with each other?

Console log your variables inside the function to see if any of them are screwy. You can also refactor that code since as you said, it is almost all the same. Less code is almost always better. At first glance it is not a scoping thing.

Lumpy fucked around with this message at 05:30 on Feb 5, 2021

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

Happy Thread posted:

So there's no way to avoid a giant history-ruining diff when you switch IDEs?

If your linting/ formatting rules are committed in the repo (.eslintrc / .prettierrc) then it should all format the same. My team uses at least 3 IDEs and we never have issues.

barkbell
Apr 14, 2006

woof

Away all Goats posted:

Total JS newbie here. I am trying to build a BMR calculator that can provide the BMR given either imperial or metric input. For some reason the imperial works fine, but the metric input returns NaN despite having nearly identical code.

Could some fresh eyes please look at this and tell me what I'm doing wrong?
code:
var system = document.getElementById("system").value;

function SystemUsage() {
    if (system == "imperial")
        CalculateImperialBMR();
    else if (system == "metric")
        CalculateMetricBMR();
}
function CalculateMetricBMR() {    
    var metricWeight = parseFloat(document.getElementById("weightKG").value);
    var metricHeight = parseFloat(document.getElementById("heightCM").value);
    var age = parseFloat(document.getElementById("age").value);
    var gender = document.getElementById("gender").value;
    var exerciselevel = document.getElementById("exerciselevel").value;
    var MaintenanceCalories = 0;

    // Using Harris-Benedit equation revised by Miifflin and St Jeor(1990):
    // Men	 BMR = (10 × weight in kg) + (6.25 × height in cm) - (5 × age in years) + 5
    // Women BMR = (10 × weight in kg) + (6.25 × height in cm) - (5 × age in years) - 161
    if (gender == "male") {
        var totalWeight = 10 * metricWeight;
        var totalHeight = 6.25 * metricHeight;
        var userAge = 5 * age;
        var result = totalWeight + totalHeight - userAge + 5;
    }

    else if (gender == "female") {
        var totalWeight = 10 * metricWeight;
        var totalHeight = 6.25 * metricHeight;
        var userAge = 5 * age;
        var result = totalWeight + totalHeight - userAge - 161;
    }

    switch (exerciselevel) {
        case "low":
            MaintenanceCalories = result * 1.53;
            break;
        case "medium":
            MaintenanceCalories = result * 1.76;
            break;
        case "high":
            MaintenanceCalories = result * 2.25;
            break;
        default: "medium";
    }

    document.getElementById("bmrResult").innerHTML = 'Your BMR is: ' + result.toFixed(2) + '<p> Your Maintenance Calories are: ' + MaintenanceCalories.toFixed(2)
} 

function CalculateImperialBMR() {

    var gender = document.getElementById("gender").value;
    var imperialHeight = (parseFloat(document.getElementById("heightFeet").value) * 12) + parseFloat(document.getElementById("heightInches").value) * 2.54;
    var imperialWeight = parseFloat(document.getElementById("weightPounds").value) / 2.205;
    var age = parseFloat(document.getElementById("age").value);
    var exerciselevel = document.getElementById("exerciselevel").value;
    var MaintenanceCalories = 0;  

    // Using Harris-Benedit equation revised by Miifflin and St Jeor(1990):
    // Men	 BMR = (10 × weight in kg) + (6.25 × height in cm) - (5 × age in years) + 5
    // Women BMR = (10 × weight in kg) + (6.25 × height in cm) - (5 × age in years) - 161
    if (gender == "male") {
        var totalWeight = 10 * imperialWeight;
        var totalHeight = 6.25 * imperialHeight;
        var userAge = 5 * age;
        var result = totalWeight + totalHeight - userAge + 5;        
    }
    else if (gender == "female") {
        var totalWeight = 10 * imperialWeight;
        var totalHeight = 6.25 * imperialHeight;
        var userAge = 5 * age;
        var result = totalWeight + totalHeight - userAge - 161;        
    }

    switch (exerciselevel) {
        case "low":
            MaintenanceCalories = result * 1.53;
            break;
        case "medium":
            MaintenanceCalories = result * 1.76;
            break;
        case "high":
            MaintenanceCalories = result * 2.25;
            break;
        default: "medium";
    }

    document.getElementById("bmrResult").innerHTML = 'Your BMR is: ' + result.toFixed(2) + '<p> Your Maintenance Calories are: ' + MaintenanceCalories.toFixed(2)
} 
is the scope of the variables interfering with each other?

you have a typo in your html

Away all Goats
Jul 5, 2005

Goose's rebellion

The html is pretty simple and just looks like this
code:
  <p><label>Height(cm): </label><input name="heightCM" size="4" tabindex="15" type="number" id="heightCM" /></p>
 <p><label>Weight(kg): </label><input name="weightKG" size="4" tabindex="17" type="number" id="weightKG" /></p>

Lumpy posted:

Console log your variables inside the function to see if any of them are screwy. You can also refactor that code since as you said, it is almost all the same. Less code is almost always better. At first glance it is not a scoping thing.

Seems like I'm getting a NaN even if I replace the result output with the variable itself :psyduck:. I've tripled checked the html side and it looks to be in order as well.

I originally had the calculator as one big function but it wasn't starting to get unwieldy for how I was trying to implement it. Guess I need to revisit that again

Empress Brosephine
Mar 31, 2012

by Jeffrey of YOSPOS
I don't see any div or html Dom element with a is of system in your code but maybe I'm just blind

Away all Goats
Jul 5, 2005

Goose's rebellion

Empress Brosephine posted:

I don't see any div or html Dom element with a is of system in your code but maybe I'm just blind

Sorry I'm not sure I understand. Are you asking about how displays the output? It just displays it below the button to calculate:

code:
<input tabindex="38" type="button" id="submit" value="Calculate" onclick="SystemUsage()" />
<input tabindex="40" type="reset" value="Reset Fields" />                                      
<p id="bmrResult">Your BMR is: </p>   

Away all Goats fucked around with this message at 06:48 on Feb 5, 2021

Jabor
Jul 16, 2010

#1 Loser at SpaceChem
Instead of posting little dribs and drabs of your stuff at a time while the people trying to help you play 20 Questions, why not just post the whole thing so people can see what's actually wrong?

Away all Goats
Jul 5, 2005

Goose's rebellion

Jabor posted:

Instead of posting little dribs and drabs of your stuff at a time while the people trying to help you play 20 Questions, why not just post the whole thing so people can see what's actually wrong?

The forums have some sort of restriction when I try to post the whole html source, even within the code brackets

https://docs.google.com/document/d/1xCxlaNbK8rB8-VgaLHvW3pe7noqdufWmwma6n1couIk/edit?usp=sharing

Jabor
Jul 16, 2010

#1 Loser at SpaceChem
getElementById() does not work with radio buttons the way you expect. Try logging the value of system where you use it to see what I mean.

An alternative you can try is to set an id on the form itself, and use form.elements["name"].value to get the value of particular inputs in the form.

You'll also want to make sure you're reading the values at the moment the user clicks the button, rather than whatever they happen to be when the page is loaded.

Adbot
ADBOT LOVES YOU

Away all Goats
Jul 5, 2005

Goose's rebellion

Thank you for the help. I did some testing and it does seem that the problem seems to in the way the radio tag passes the information in to the function since it keeps returning a NaN value. I tried switching it to a select tag but no dice. Tried the form.elements method and adding an eventlistener and still keeps returning a NaN.

I've been smashing my head against this wall for a few hours now so I think I'll take a break. Thanks again though. Maybe I'll just have each calculator on its own separate page :shepface:

  • 1
  • 2
  • 3
  • 4
  • 5
  • Post
  • Reply