I'm trying to allow cors on grunt connect task that hosts the angular app. *I'm using angular yeoman generator. Here is what i've tried so far:
connect: {
options: {
port: 9004,
hostname: 'localhost',
livereload: 35728,
middleware: function(connect, options) {
return [
function(req, res, next) {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
res.setHeader('Access-Control-Allow-Headers', 'Content-Type');
return next();
},
connect.static(require('path').resolve(yeomanConfig.app))
];
}
},
When i load localhost:9004 i want to have access-control-allow-origin:* in headers
Related
So basically I'm trying to migrate from Vue-cli to vite and I need to find an alternative to
module.exports = {
publicPath: '',
devServer: {
setup(app) {
app.post('*', (req, res) => {
res.redirect(req.originalURL);
});
},
},
lintOnSave: false
};
for developing apps with Bitrix api
I have a cors issue in my development with vue3 & vite, so I create a proxy config in my vite.config.js
import { defineConfig } from 'vite'
import vue from '#vitejs/plugin-vue'
import { resolve } from 'path'
export default defineConfig({
plugins: [vue()],
resolve: {
alias: {
'#': resolve(__dirname, 'src'),
},
},
server: {
proxy: {
"/api": {
target: "https://###.com",
changeOrigin: true,
secure: false,
rewrite: (path) => path.replace(/^\/api/, ""),
},
}
}
})
when I use in my app my method:
createPayment() {
const url = "/api/webhook/###";
let formData = new FormData();
formData.append("firstName", this.first_name);
formData.append("lastName", this.last_name);
formData.append("email", this.email);
formData.append("phone", this.phone);
formData.append("cardNumber", this.c_number);
formData.append("cardExpiration", this.c_EXP);
formData.append("cardCCV", this.c_CVC);
const request = new Request(url, {
method: "POST",
body: formData,
headers: {
accept: 'application/json',
contentType: "application/json;charset=UTF-8",
AccessControlAllowOrigin: '*'
},
});
fetch(request)
.then(result => console.log(result))
.catch(error => console.log('error', error));
},
The Post all ways send from localhost, I can't understand why?
I make the config for change '/api' to 'https://###.com' ?
My Log:
Response {type: 'basic', url: 'http://localhost:3000/api/webhook/####', redirected: false, status: 404, ok: false, …}
Having a bit of a problem with Grunt server using proxies.
I have everything working fine, however, when I submit a post request I get a 200 success from my proxy.
Then with each subsequent use of that proxy I get a 504 Gateway Timeout.
For instance if I post to student-minors proxy it goes through fine.
Every time after that I get a 504 when I try to do something else with that proxy.
I can use the other proxies with a get, I can get terms and courses.
Seems like something is either hanging, throwing an error of some kind, but I can't see it.
Any insight would be appreciated.
Here is a snippet of the connect server with the proxy stuff
// Define the configuration for all the tasks
grunt.initConfig({
connect: {
rules: [
{from: '^/poc-proxy/(.*)$', to: '/authorizations/$1'},
{from: '^/service/apis/terms/(.*)$', to: '/terms/$1'},
{from: '^/service/apis/courses/(.*)$', to: '/courses/$1'},
{from: '^/service/apis/studentMinors/(.*)$', to: '/studentMinors/$1'}
],
server: {
options: {
port: 9000,
base: 'dev',
hostname: 'localhost',
middleware: function (connect, res,options, middlewares) {
return [
rewriteRules,
serveStatic('./dev'),
require('grunt-middleware-proxy/lib/Utils').getProxyMiddleware()
]
}
},
proxies: [{
context: '/authorizations', //REQUIRED! Must start with a '/' should not end with a '/'
host: 'authorizations.com', //REQUIRED! Should not contain 'http://' or 'https://'
changeOrigin: true,
https: true,//Optional, defaults to false
headers: {//Optional.
'Access-Control-Allow-Origin': '*'
}
},
{
context: '/terms', //REQUIRED! Must start with a '/' should not end with a '/'
host: 'terms.com', //REQUIRED! Should not contain 'http://' or 'https://'
changeOrigin: true,
https: true,//Optional, defaults to false
headers: {//Optional.
'Access-Control-Allow-Origin': '*'
}
},
{
context: '/courses', //REQUIRED! Must start with a '/' should not end with a '/'
host: 'courses.com', //REQUIRED! Should not contain 'http://' or 'https://'
changeOrigin: true,
https: true,//Optional, defaults to false
headers: {//Optional.
'Access-Control-Allow-Origin': '*'
}
},
{
context: '/studentMinors', //REQUIRED! Must start with a '/' should not end with a '/'
host: 'minors.com', //REQUIRED! Should not contain 'http://' or 'https://'
https: true,
changeOrigin: true,
headers: {//Optional.
'Access-Control-Allow-Origin': '*'
}
}
]
}
},
Changed the server options.
server: {
options: {
port: 9000,
base: 'dev',
hostname: 'localhost',
middleware: function (connect, res,options, middlewares) {
return [
rewriteRules,
serveStatic('./dev'),
//require('grunt-middleware-proxy/lib/Utils').getProxyMiddleware()
require('grunt-connect-proxy/lib/utils').proxyRequest
]
}
},
Changed the task run
grunt.registerTask('serve', 'start the server and preview your app', function (target) {
if (target === 'dist') {
return grunt.task.run(['build', 'browserSync:dist']);
}
grunt.task.run([
'configureRewriteRules',
//'setupProxies:server',
'configureProxies:server',
'connect:server',
'clean:server',
'wiredep',
'concurrent:server',
'postcss:dev',
'copy:dev',
//'browserSync:livereload', //Browsersync a proxy servers conflict with CORS
'watch'
]);
});
When I try using Grunt to create a server for me it quickly shuts down and doesn't give me a change to go to my browser and test it.
This is my entire Grunt file:
module.exports = function (grunt) {
grunt.loadNpmTasks('grunt-contrib-connect');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.initConfig({
connect: {
serve: {
options: {
port: 8081,
base: '/',
hostname: '*',
debug: true
}
}
}
});
grunt.registerTask('default', ['connect']);
}
When I run it, it works without errors:
C:\Users\Imray\my-sandbox>grunt
Running "connect:keepalive" (connect) task
Started connect web server on http://0.0.0.0:8000
Running "connect:serve" (connect) task
Started connect web server on http://0.0.0.0:8081
You have the keepalive settings dedicated for this :
grunt.initConfig({
connect: {
serve: {
options: {
keepalive: true,
port: 8081,
base: '/',
hostname: '*',
debug: true
}
}
}
});
Does anyone know the best solution for automatically restarting node and running tests after the restart every time a file changes?
I am currently using grunt-contrib-watch with grunt-develop. I am getting an ECONNREFUSED error on the some restarts. I think it is because my tests are running before the server is fully online.
Any ideas on how best to achieve what I want?
What I want: Restart node and then run all integration tests after each file change.
I am taking a BDD approach to testing (as opposed to regular unit tests) with cucumber.js. I wanted to make sure that each test run against the API I was building started on a fresh boot-up of the application.
I figured it out. Here is what I used:
grunt-contrib-watch to monitor for file changes.
It in turn calls
grunt-develop to restart the application
grunt-cucumberjs to run the cucumber tests
I then modified my index.js (starts the app) so that it doesn't start the app if the NODE_ENV is set to test. That way the cucumber tests actually start the server and can wait till the start process has finished before running the tests.
Here is the GruntFile and Index file:
Gruntfile.js
/*jslint node: true */
"use strict";
module.exports = function(grunt) {
// Project configuration.
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
env: {
dev: {
APP_DIR_FOR_CODE_COVERAGE: 'coverage/instrument/',
NODE_ENV: 'dev',
PORT: 8080
},
test: {
APP_DIR_FOR_CODE_COVERAGE: 'coverage/instrument/',
NODE_ENV: 'test',
PORT: 8081
},
coverage: {
APP_DIR_FOR_CODE_COVERAGE: 'coverage/instrument/',
NODE_ENV: 'test',
PORT: 8081
}
},
watch: {
js: {
files: [
'index.js',
'features/**/*.js',
'server/**/*.js'
],
tasks: ['develop', 'cucumberjs', 'jshint'],
options: {
nospawn: true
}
}
},
jshint: {
all: ['Gruntfile.js', 'index.js', 'server/**/*.js', 'features/**/*.js']
},
nodemon: {
dev: {
script: 'index.js'
}
},
cucumberjs: {
src: './features',
},
develop: {
server: {
file: 'index.js'
}
},
instrument: {
files: ['index.js', 'server/**/*.*'],
options: {
lazy: true,
basePath: 'coverage/instrument/'
}
},
storeCoverage: {
options: {
dir: 'coverage'
}
},
makeReport: {
src: 'coverage/coverage.json',
options: {
type: 'lcov',
dir: 'coverage/reports',
print: 'detail'
}
},
coverage: {
options: {
thresholds: {
'statements': 90,
'branches': 90,
'lines': 90,
'functions': 90
},
dir: 'coverage',
root: ''
}
}
});
grunt.loadNpmTasks('grunt-env');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-develop');
grunt.loadNpmTasks('grunt-cucumber');
grunt.loadNpmTasks('grunt-istanbul');
grunt.loadNpmTasks('grunt-istanbul-coverage');
grunt.loadNpmTasks('grunt-nodemon');
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.registerTask('default', ['env:dev', 'nodemon']);
grunt.registerTask('test', ['env:test', 'watch']);
grunt.registerTask('testcoverage', ['env:test', 'jshint', 'instrument', 'cucumberjs', 'storeCoverage', 'makeReport', 'coverage']);
};
Index.js
/*jslint node: true */
"use strict";
var Hapi = require('hapi');
var Good = require('good');
var server = {};
exports.server = {
start: function(callback) {
/* istanbul ignore next */
var port = process.env.PORT || 8080;
server = new Hapi.Server(port);
var routes = require('./server/routes');
routes.register(server);
var exceptionHandling = require('./server/exceptionHandling');
exceptionHandling.register(server);
server.pack.register(Good, function(err) {
/* istanbul ignore if */
if (err) {
throw err; // something bad happened loading the plugin
}
/* istanbul ignore next */
server.log('info', 'Server starting at ' + server.info.uri);
server.start(callback);
});
},
stop: function(callback) {
server.log('info', 'Server stopping.');
server.stop(null, callback);
},
rootUrl: function() { return server.info.uri; }
};
/* istanbul ignore if */
if (process.env.NODE_ENV != 'test') {
exports.server.start(function() {});
}