Angular 5 call api with CORS - node.js

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

Related

File serve in shopify app dev not working

I've created shopify app with node.js app template
npm init #shopify/app#latest
Folder structure is at the bottom
And run npm run dev
It's ok for api endpoints.
What I wanna do is to serve static files. In fact, this is an express.js server and I created a static folder in web folder
app.use(serveStatic('static'));
But I can't access static files. I tried app.use(serveStatic("${process.cwd()}/static")). The above stuff is working on a normal express.js project. But it does not work with shopify cli and vite config.
Vite config is
const config = {
test: {
globals: true,
exclude: ["./frontend/**", "./node_modules/**"],
},
};
export default config;
I finally got it.
I noticed that:
It works if you were to load using localhost:PORT/path/to/static.file. You can print out PORT in your web/index.js.
This simple middleware doesn't get triggered when requesting your static file through ngrok but it does get triggered by number 1 above.
app.use((req, res, next) => {
console.log("Backend hit!");
next();
});
That means the backend never got the static file request. My understanding is vite receives all the requests then proxies some of them to the backend using a config.
The config Shopify gave is not proxying the static file request so you'll need to modify the proxy config.
vite.config
...
export default defineConfig({
...
server: {
host: "localhost",
port: process.env.FRONTEND_PORT,
hmr: hmrConfig,
proxy: {
"^/(\\?.*)?$": proxyOptions,
"^/api(/|(\\?.*)?$)": proxyOptions,
// The next line is what I added
"^/static/.*$": proxyOptions,
},
},
});
web/index.js
app.use("/static", express.static(`${process.cwd()}/public`));
I'm mounting my static files on "/static" but feel free to modify the proxy line to suit your needs.

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.

Deploying React Express and Node app to Heroku Proxy Error

I have successfully in the past launched full stack applications to Heroku by using within the client package.json file.
"proxy": "http://localhost:3001"
Now I am getting an "Invalid Host header" I did fix that error by removing the proxy as well as implementing setupProxy.js file with the following code, but afterwards the app does not call the back end at all and errors out.
const { createProxyMiddleware } = require('http-proxy-middleware');
module.exports = function(app) {
app.use(
'/api',
createProxyMiddleware({
target: 'http://localhost:3001',
changeOrigin: true,
})
);
};
I'm wondering how to fix, or if anything changed recently in Heroku to not allow proxy within the client package.json file?
It looks like it was a seemingly unrelated fix. I had to enter in some environment variables within Heroku to allow the server to run. Without the variables, I believe the server would stop with errors therefore trickling down and causing many problems. So long story short, always remember your environment variables within Heroku.

How to setup gulp browser-sync for a node / react project that uses dynamic url routing

I am trying to add BrowserSync to my react.js node project. My problem is that my project manages the url routing, listening port and mongoose connection through the server.js file so obviously when I run a browser-sync task and check the localhost url http://localhost:3000 I get a Cannot GET /.
Is there a way to force browser-sync to use my server.js file? Should I be using a secondary nodemon server or something (and if i do how can the cross-browser syncing work)? I am really lost and all the examples I have seen add more confusion. Help!!
gulp.task('browser-sync', function() {
browserSync({
server: {
baseDir: "./"
},
files: [
'static/**/*.*',
'!static/js/bundle.js'
],
});
});
We had a similar issue that we were able to fix by using proxy-middleware(https://www.npmjs.com/package/proxy-middleware). BrowserSync lets you add middleware so you can process each request. Here is a trimmed down example of what we were doing:
var proxy = require('proxy-middleware');
var url = require('url');
// the base url where to forward the requests
var proxyOptions = url.parse('https://appserver:8080/api');
// Which route browserSync should forward to the gateway
proxyOptions.route = '/api'
// so an ajax request to browserSync http://localhost:3000/api/users would be
// sent via proxy to http://appserver:8080/api/users while letting any requests
// that don't have /api at the beginning of the path fall back to the default behavior.
browserSync({
// other browserSync options
// ....
server: {
middleware: [
// proxy /api requests to api gateway
proxy(proxyOptions)
]
}
});
The cool thing about this is that you can change where the proxy is pointed, so you can test against different environments. One thing to note is that all of our routes start with /api which makes this approach a lot easier. It would be a little more tricky to pick and choose which routes to proxy but hopefully the example above will give you a good starting point.
The other option would be to use CORS, but if you aren't dealing with that in production it may not be worth messing with for your dev environment.

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