Cross-site POST form submissions are forbidden - node.js

My sveltekit app has a form which sends a POST request to server. The app is working fine on dev server but when I build and run the app it fails to send the form data via POST request. It shows the following error in the browser:
Cross-site POST form submissions are forbidden

You have to set the the ORIGIN env var like this
ORIGIN=http://localhost:3000 node build/index.js
https://github.com/sveltejs/kit/tree/master/packages/adapter-node#origin-protocol_header-and-host_header

This is a built-in protection against cross-site request forgery attacks in Sveltekit. Set csrf to false in svelte.config.js to allow cross-site post requests.
See csrf in the Sveltekit configuration docs
import adapter from '#sveltejs/adapter-node'
const config = {
kit: {
adapter: adapter(),
csrf: {
checkOrigin: false,
}
},
}
export default config

This works: node -r dotenv/config build after including your new variable in .env ORIGIN=https://yourwebsite.com (please install it with npm install dotenv command as pointed out here)

Related

How do I proxy requests for static files on my node server to my react development server?

I have a node.js server that serves the built static files of my create-react-app at /admin. The problem is that anytime I make a change to my react app I have to build the files over again to see the updates. Instead, I'd like to proxy requests for my frontend at /admin to my dev server that comes with create-react-app, running at localhost:3000, because this would allow for a much faster development experience.
This is what my server looks like now:
// app.ts
...
const app: Koa = new Koa();
app.use(mount('/admin', serve(__dirname + '/build')));
...
And this is what I tried:
import proxy from 'koa-better-http-proxy';
const app: Koa = new Koa();
app.use(
mount(
'/admin',
proxy('localhost:3000', {})
)
)
What ends up happening is the requests for static files still go out and the response gives an index.html file but the JS doesn't seem to run and it gives me errors:
Uncaught SyntaxError: Unexpected token '<'
I've also played around with the proxy header settings to adjust content-type to application/json but I had no success there either.
Due to the environment, I cannot just run the node server in one terminal and the react app in another. The request comes from a verified 3rd party and must go through my node server first before being served the frontend portion of my app.

Connecting front end and back end React / Node.js

I am trying to create an account through my registration form, however I keep on getting this error:
This is my registration form:
However when I press Register, get this error:
Commands: npm start
Errors: Proxy error: Could not proxy request /users/register from localhost:3000 to http://localhost:5000.
See https://nodejs.org/api/errors.html#errors_common_system_errors for more information (ECONNREFUSED).
Error photo:
Much appreciated, thank you in advance.
Problem solved: Needed to start the React and the Node project on two different terminals, first run the React and then the Node project
Enable cors in your server
if Node and express
then add cors package and then in the entry point file ( index.js or app.js )
add this along with other imports
const cors = require('cors');
and then after your app is initialised then add this line
app.use(cors());
and also add these lines to the header of your request on the react side
'Access-Control-Allow-Origin': '*',
if you are using axios then I suggest you creating a separate file for axios
import axios from 'axios';
export default axios.create({
baseURL: 'http://localhost:8000',
headers: {
'Access-Control-Allow-Origin': '*',
'Content-Type': 'application/json'
}
});
there you configure your common axios details and import this file instead of the package wherever you using axios on react
If still facing an issue then please copy paste the error as it shows on the network tab
I think the solution to this is to run node server.js instead of npm start

Angular 5 call api with CORS

Hello i am creating an Angular application that i need to call an API. I have run into the CORS Error. "No Access-Control-Allow-Origin" which I have found a few things on line about but I still do not understand where I am supposed to add the middlewhere. I wonder if someone could be specific on how to get this to work with angular cli.
If you open a command prompt and type ng new test then open that test folder up and type npm start. you add the code to call an api lets say localhost/someapi/api/people but because you're not calling localhost:4200 you get this error.
So just so that my question is clear, I understand that you need to add the cors middle where on the server. But the question is, where in the angular 5 app do I add this for node to read it and allow this to work?
Below is the code that I'm using to call api.
getToken():void{
let headers = new Headers({'Content-type': 'application/x-www-form-urlencoded'})
let params = new URLSearchParams();
params.append('username','some-username');
params.append('password', 'some-encripted-password');
params.append('grant_type', 'password');
let options = new RequestOptions();
options.headers = headers;
this.http
.post(this.appConfig.baseRoute + 'token',params.toString(), options)
.subscribe(result=>{ });
}
CORS headers should be set in server-side as per the answer in the link that you provided. There shouldn't be anything to set on the Angular client side other than maybe authentication tokens if you server requires them.
To ease your development locally, you could set up a proxy for ng serve.
Add this file in your root (folder with angular-cli.json)
proxy.conf.js
const PROXY_CONFIG = [
{
context: [
// what routes to proxy
"/api",
],
// your backend api server
target: "http://localhost:8000",
secure: false
}
]
module.exports = PROXY_CONFIG;
instead of calling ng serve, use ng serve --proxy-config proxy.conf.js

Sails.js API passport.js authentication

I am trying to develop an API backend in Sails.js.
The most basic thing which I require is authentication.
With that, I found the sails-generate-auth generator, I have followed all the steps listed at
sails-generate-auth .
Now, when I access http://localhost:1337/register, I see a simple registration form, same goes for login, and after logging in, I see a cookie set in my browser as sails.sid.
After inspecting the AuthController.js I see that it has been written for server rendered views.
How should I modify the controller/sailsApp so that it supports API based authentication.
I would ideally like to have:
A register route which would accept username and password via post
with content type application/json.
Login route which would accept username and password with
content-type application/json and return with a bearer token so that the frontend app can add it to its header the next time it makes a request.
All other routes under an auth ACL which would check if the bearer
token is present and is verified.
In your AuthController callback function replace this:
res.redirect('/');
with this:
console.log(user);
var userID = user.id;
Passport.find({user: userID}, function(err, items){
if(err) return err;
console.log(items[0].accessToken);
// Make sure you dont give them any sensetive data
res.json({userData: user, token: items[0].accessToken});
});
// Upon successful login, send the user to the homepage were req.user
//res.redirect('/');
Now when the client sends a login/register request the server will response with a JSON response. Make sure you request the token on your other sails app actions.
Ive been using these steps for a while now.
Step 1 ( Globals ): $ npm install -g sails
Step 2 ( App ): $ sails new myApp
Step 3 ( Files ): Copy every file in https://github.com/carlospliego/sails-token-auth-setup to its corresponding folder
Step 4 ( Policies ): Add this code to your config/policies.js
'*': "hasToken",
UserController: {
"create": true
},
AuthController: {
'*': true
}
Step 5: change the value of config/tokenSecret.js
Step 6: ( Dependencies )
npm install --save passport
npm install --save passport-local
npm install --save bcrypt-nodejs
npm install --save jsonwebtoken
npm install --save express-jwt
Your endpoints will look like this:
POST/GET/PUT/DELETE user/
POST auth/login
DELETE auth/logout
Here is a great guide on how to create token based authentication in sails: https://github.com/carlospliego/sails-token-auth-setup

yeoman 1.0 - make development server accept POST calls

I'm using yeoman for my application which consists of 2 parts - client site with js/html/css and the rest service.
During development I start rest service in Eclipse and start server for my static files with
grunt server
The problem is that I have to do a post request to root url '/' (it's a fake login POST request to make browsers prompt to save passwords).
It worked with yeoman 0.9 but after updating I get:
Cannot POST /
Is there a way to configure grunt server task to accept POST requests?
Thanks!
Leonti
I think you want the connect-rest middleware.
https://github.com/imrefazekas/connect-rest
npm install connect-rest --save-dev
Edit Gruntfile.js, at the top
var restSupport = require('connect-rest');
restSupport.post( { path: '/savequestion'}, function(req, content, next){
next(null, {result: 'OK'});
});
In your connect or livereload middleware section:
livereload: {
options: {
middleware: function (connect) {
return [
lrSnippet,
mountFolder(connect, '.tmp'),
mountFolder(connect, yeomanConfig.app),
restSupport.rester( {'context': '/forms'} ),
rewriteRulesSnippet, // RewriteRules support
The key part is "restSupport.rester()", remove the context if you don't want it.
This simple function should just reply with the json object {result: 'OK'} to everything you post to /forms/savequestion . It should at least let you build out scaffolding in grunt server :9000 mode before you have build your templates. Without this you would have to $.get() each $.post() and then change it during or after the build.

Resources