Angular2 error after deployment on AWS server ""Only void and foreign elements can be self closed "head" ("[ERROR ->]<head/>" - apache

After having finished and tested an Angular2 application on my local machine, I decided to move it to an AWS cloud server with Apache.
I cloned the sw from git but, as soon as I launched the app, I got an error on the browser console stating:
EXCEPTION: Template parse errors:
Only void and foreign elements can be self closed "head" ("[ERROR ->]<head/>
After some research I found that all of my external html templates are magically enriched with a starting <head/> tag which I do not see trace of in my code.
To fix this I had to turn off mod-pagespeed .Since I am not familiar with Apache configuration I do not know which side effects this may have and whether there is any better solution. Any help would be very much appreciated.

I believe mod-pagespeed has an option where it automatically adds a head tag to an html document if it cannot find it in the document (before the body). To turn off this feature add this to your pagespeed apache configuration (ie. in the .htaccess):
To prevent javascript alterations also forbid a couple more filters
ModPagespeedForbidFilters add_head,rewrite_javascript,rewrite_javascript_inline,combine_javascript,inline_javascript
This way you can still enjoy the rest of the mod-pagespeed features :)

Related

Stencil not working with a 500 server error

Using stencil 3.0.3, node 12.21 cornerstone theme was working and suddenly stopped with a weird server error:
Debug: internal, implementation, error
Error: The BigCommerce server responded with a 500 error
at Object.internals.getResponse (/usr/local/lib/node_modules/#bigcommerce/stencil-cli/server/plugins/renderer/renderer.module.js:128:15)
at processTicksAndRejections (internal/process/task_queues.js:97:5)
at async internals.implementation (/usr/local/lib/node_modules/#bigcommerce/stencil-cli/server/plugins/renderer/renderer.module.js:39:20)
at async module.exports.internals.Manager.execute (/usr/local/lib/node_modules/#bigcommerce/stencil-cli/node_modules/#hapi/hapi/lib/toolkit.js:45:28)
at async Object.internals.handler (/usr/local/lib/node_modules/#bigcommerce/stencil-cli/node_modules/#hapi/hapi/lib/handler.js:46:20)
at async exports.execute (/usr/local/lib/node_modules/#bigcommerce/stencil-cli/node_modules/#hapi/hapi/lib/handler.js:31:20)
at async Request._lifecycle (/usr/local/lib/node_modules/#bigcommerce/stencil-cli/node_modules/#hapi/hapi/lib/request.js:312:32)
at async Request._execute (/usr/local/lib/node_modules/#bigcommerce/stencil-cli/node_modules/#hapi/hapi/lib/request.js:221:9)
I have tried to re-install big commerce stencil, clean build and still get the same error.... at this point I have no idea what could be causing this issue.
Importantly, there was no code changes in between the day where everything was working and the day where it stopped.
Are you using CloudFlare for a CDN? I've ran into this issue and have had to edit my hosts file
I add the following 3 lines.
The first one is for the Store Domain, i.e. if you have MyShoeStore.com
The second 2 contain the auto-generated store-hash for a BigCommerce store that should be visible in your URL bar if you are on the BigCommerce control panel (Logged into the admin view - that's the easiest way to get it, there are some others)
35.186.223.98 mystoredomain.com
35.186.223.98 store-abcdefg[store-hash].mybigcommerce.com
35.186.223.98 www.store-abcdefg[store-hash].mybigcommerce.com
For some reason, Stencil-CLI gets thrown for a loop when trying to connect to a BigCommerce store that is running behind CloudFlare CDN. This has caused 500 errors in the Stencil-CLI, and a failure to render, during local development, but the store is able to be uploaded and hosted in production without a problem.
I'm not sure if this is the actual issue that you had which caused your 500 error, (It can be due to an error in the syntax of one of the HandleBars templates, but usually Stencil-CLI will output an informative error for that reason.)
The other situation I have seen this in is if you are trying to run Cornerstone on a very old BigCommerce store which is still running their old template framework (Blueprint) - in that situation, certain pages will 500, but others will work.
This may be helpful for others who are running into this.
I installed a proxy tool to capture traffic between stencil and BigCommerce in order to perhaps find more details on this error.
Unfortunately, as soon as I did that, the site worked again...

How to solve flutter web api cors error only with dart code?

It seems like CORS error is well-known issue in the web field. But I tried flutter web for the first time ever and I faced critical error.
The code below worked well in app version when it was running on iOS device, but when i tested the same code on Chrome with web debugging from beta channel, it encountered CORS error.
Other stackoverflow answers explained how to solve the CORS issue with serverside files of their projects. But I have totally no idea what is server thing and how to deal with their answers. The error message from Chrome console was below
[ Access to XMLHttpRequest at 'https://kapi.kakao.com/v1/payment/ready' from origin 'http://localhost:52700' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. ]
So, what i want to do is to solve above 'Access-Control-Allow-Origin header' issue ONLY WITH DART CODE! Code below is what i've tried to solve these issues only with my main.dart.
onPressed: () async {
var res =
await http.post('https://kapi.kakao.com/v1/payment/ready', encoding: Encoding.getByName('utf8'), headers: {
'Authorization': 'KakaoAK $_ADMIN_KEY',
HttpHeaders.authorizationHeader: 'KakaoAK $_ADMIN_KEY',
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "POST, GET, OPTIONS, PUT, DELETE, HEAD",
}, body: {
'cid': 'TC0ONETIME',
'partner_order_id': 'partner_order_id',
'partner_user_id': 'partner_user_id',
'item_name': 'cool_beer',
'quantity': '1',
'total_amount': '22222',
'vat_amount': '2222',
'tax_free_amount': '0',
'approval_url': '$_URL/kakaopayment',
'fail_url': '$_URL/kakaopayment',
'cancel_url': '$_URL/kakaopayment'
});
Map<String, dynamic> result = json.decode(res.body);
print(result);
},
Even though i actually had the header "Access-Control-Allow-Origin": "*" which most other answers recommended, the Chrome console printed same error message. Weird thing is that the same code made successful request in mobileApp version. So I think this is only problem with flutter WEB VERSION.
Hope somebody can figure it out and suggest only-dart code to resolve the issue in my main.dart!! Thank you for reading [:
1- Go to flutter\bin\cache and remove a file named: flutter_tools.stamp
2- Go to flutter\packages\flutter_tools\lib\src\web and open the file chrome.dart.
3- Find '--disable-extensions'
4- Add '--disable-web-security'
Since Flutter 3.3.0
I implemented the option to add any browser flag to the flutter command.
flutter run -d chrome --web-browser-flag "--disable-web-security"
Or for drive command:
flutter drive --driver=test_driver/integration_test.dart --target=integration_test/app_test.dart -d web-server --web-browser-flag="--disable-web-security"
Note: This is just for development and testing. Flutter is executed explicitly on the client's browser! You should NOT and you can NOT disable it in production (as stated by #Tommy), as it is a security feature of the browser, and not meant to be changed in dart code. You have to enable CORS on your web server, which is providing the resources of your Flutter app, to ensure it works for everyone.
If you use dart language without Flutter on the server side with shelf, then see this response.
I think disabling web security as suggested will make you jump over the current error for now but when you go for production or testing on other devices the problem will persist because it is just a workaround, the correct solution is from the server side to allow CORS from the requesting domain and allow the needed methods, and credentials if needed.
run/compile your Flutter web project using web-renderer. This should solve the issue both locally and remotely:
flutter run -d chrome --web-renderer html
flutter build web --web-renderer html
This is a CORS (cross-origin resource sharing) issue and you do not have to delete/modify anything. You just have to enable the CORS request from your server-side and it will work fine.
In my case, I have created a server with node.js and express.js, so I just added this middleware function that will run for every request.
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Methods", "GET,PUT,PATCH,POST,DELETE");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
And BOOOOM! I received the data.
You just have to look at the settings to enable CORS for your server.
Server side engine like node js or django is really needed to work with flutter web with bunch of external apis. Actually there's high possibility of same CORS error when we try to use internal api because of the CORS mechanism related to port number difference.
There are bunch of steps and answers from SO contributors that recommend to use chrome extensions to avoid CORS errors, but that is actually not cool for users. All the users should download the browser extensions to use the single website from us, which wouldn't be there if we used true server engines.
CORS is from browser as far as i know, so our flutter ios and android apps with same api code don't give those CORS errors. First time i encountered this error with flutter web, i believed i can deal with CORS in my app code lines. But that is actually not healthy way for users and long term dev plans.
Hope all flutter web newbies understand that web is quite a wild field for us. Even though i'm also newbie here, i highly recommend all the flutter web devs from 1.22.n stable to learn server side engines like node js. It is worth try.
And if u came so far down to this line of my self-answer, here's a simple guide for flutter web with node js. Flutter web is on stable channel but all those necessary infra are not fully ready for newbies like me. So be careful when you first dive into web field, and hope you re-check all the conditions and requirements to find out if you really need web version of your flutter app, and also if you really need to do this work with flutter. And my answer was yes lol
https://blog.logrocket.com/flutter-web-app-node-js/
If you run a Spring Boot server, add "#CrossOrigin" to your Controller or to your service method.
#CrossOrigin
#PostMapping(path="/upload")
public #ResponseBody ResponseEntity<Void> upload(#RequestBody Object object) {
// ...
}
I know the question explicitly asked for a solution "with dart code" only, but I was not able to fix the exception with dart code (for example by changing the header).
The disabling web security approaches work well in development, but probably not so well in production. An approach that worked for me in production dart code involves avoiding the pre-flight CORS check entirely by keeping the web request simple. In my case this meant changing the request header to contain:
'Content-Type': 'text/plain'
Even though I'm actually sending json, setting it to text/plain avoids the pre-flight CORS check. The lambda function I'm calling didn't support pre-flight OPTIONS requests.
Here's some info on other ways to keep a request simple and avoid a pre-flight request
https://docs.flutter.dev/development/platform-integration/web-images
flutter run -d chrome --web-renderer html
flutter build web --web-renderer html
This official solution worked for me on Chrome only (Source). But I had to run it first every time.
flutter run -d chrome --web-renderer html
And disabling web security also worked (Source). But the browsers will show a warning banner.
But In case you are running on a different browser than Chrome (e.g. Edge) and you want to keep 'web security' enabled.
You can change the default web renderer in settings in VS Code
File ==> Preferences ==> Settings ==> Enter 'Flutter Web' in the Search Bar ==> Set the default web renderer to html
After hours of testing, the following works perfectly for me.
Add the following to the PHP file:
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST');
header("Access-Control-Allow-Headers: X-Requested-With");
This allow the correct connection with the HTTP GET POST with no issue from flutter for me.
I discovered this in the following discussion:
XMLHttpRequest error Flutter
I am getting the same error with php api so i add the php code these lines ;
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST');
header("Access-Control-Allow-Headers: X-Requested-With");
I think you may not doing this in right way.
The cors headers should be added in HTTP response header while you added them in you reuqest header obviously.
for more information check out the documentation https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS#what_requests_use_cors
The below solution is great if you are only communicating with a local NodeJS server.
Install NodeJS
Create a basic NodeJS express project
Create a folder to put you NodeJS project in
ex: C:\node_project\
in PowerShell run: npm init in the folder
fill in your desired values
entry point: must be app.js for this example to work
in PowerShell run: npm install express in the folder
create a app.js file in the folder
// init express
const express = require("express");
const app = express();
// set the path to the web build folder
app.use(express.static("C:/Users/your_username/path_to_flutter_app/build/web"));
const PORT = process.env.PORT || 8080;
app.listen(PORT, () => {
console.log(`Server listening on port ${PORT}...`);
});
The value "C:/Users/your_username/path_to_flutter_app/build/web" must be changed to the web build folder in your flutter app.
The app can be accessed through your browser once the app is built, the node server is running, and the browser is at the correct address
Build the app
open PowerShell and navigate to the flutter project's root ex: C:/Users/your_username/path_to_flutter_app/
run flutter build web
turn on the node server
open PowerShell and navigate to the NodeJS server folder ex: C:\node_project\
run: node app.js
Open in your browser
Enter http://localhost:8080/ into the browser
Note that everytime you change your flutter app's dart code you will need to re-run flutter build web
Wrong Server on Target Port 🤦
I feel silly for even admitting this, but I had some other local server running on the targeted port. I've no clue why the server seemed to boot on the same port, or why the iOS app seemed to work, but now that I'm hitting the actual server it's working fine.
I was also getting some 404's mixed in, but originally thought that was due to the CORs error.
Maybe someone else has this same issue and this helps them.
In my case, The problem was in laravel backend code which did not support CORS, So I added the CORS into backend project then it worked successfully in test and live.
The 5th step of Osmans answer should be to add the option
'--disable-site-isolation-trials',
Only this works for me.
Chrome version 106.0.5249.119
Update:
I recommend to use User Rebo's answer. It is now possible to pass --disable-web-security as a browser flag to run & drive commands!
Original outdated answer:
Alternative solution for MacOS & Android Studio (without modifying Flutter source)
We use a similar approach as Osman Tuzcu. Instead of modifying the Flutter source code, we add the --disable-web-security argument in a shell script and just forward all other arguments that were set by Flutter. It might look overly complicated but it takes just a minute and there is no need to repeat it for every Flutter version.
1. Run this in your terminal
echo '#!/bin/zsh
# See also https://stackoverflow.com/a/31150244/410996
trap "trap - SIGTERM && kill -- -$$" SIGINT SIGTERM EXIT
set -e ; /Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome --test-type --disable-web-security "$#" ; set +e &
PID=$!
wait $PID
trap - SIGINT SIGTERM EXIT
wait $PID
' > ~/chrome_launcher
chmod 755 ~/chrome_launcher
This adds a chrome_launcher script to your user folder and marks it executable.
2. Add this line to your .zshrc (or .bashrc etc.):
export CHROME_EXECUTABLE=~/chrome_launcher
3. Restart Android Studio
If a simple restart does not work, use Invalidate Caches / Restart in Android Studio to force loading of changes.
Notes
The script also adds the --test-type flag to suppress the ugly warning about the disabled security features. Be aware that this option might also suppress other error messages!
The CHROME_EXECUTABLE takes only the path to an executable file it is not possible to set arguments there.
Without trapping exit signals and killing the process group, the Google Chrome instance was not killed when you hit the Stop Button in Android Studio.
If you are using FVM, I suggest to use flutter_cors package
dart pub global activate flutter_cors
fluttercors --disable
If you face
zsh: command not found: fluttercors
You need to add it to PATH. In my case, I'm using zsh, I add it to .zshrc by
vim ~/.zshrc
Press I to start editing and paste export PATH="$PATH":"$HOME/.pub-cache/bin" to the top of the file
Then press ESC and type :wq to save the .zshrc file.
Now you're good to go
Now, just need to run your flutter web normally. It will trigger Chrome without CORS.
For me none of the solutions above worked on production as it was expected. Altough there is one solution I can suggest which uses CORS proxy to avoid CORS issues on flutter web on production. You can find CORS proxies on this website.
Basically you bypass all the unnecessary headers which your browser appends to your requests, so you may not encounter the same CORS issues when making request to another API. Hope it helps!
It Worked With Me By The Following Code :
in conn.php file put like this :
<?php
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST');
header("Access-Control-Allow-Headers: X-Requested-With");
$connect = new mysqli("localhost","db_user","db_password","db_name");
if($connect){
}else{
echo "Connection Failed";
exit();
}
This is a CORS (cross-origin resource sharing) issue and you just need to enable the CORS request from your server-side.
In my case it is Asp.Net MVC Web API and adding below code to Application_BeginRequest at Global.asax worked for me:
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "http://localhost:7777/");
if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
{
//These headers are handling the "pre-flight" OPTIONS call sent by the browser
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "POST, GET");
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "content-type");
HttpContext.Current.Response.End();
}
Use desired urls , Methods and Headers
Also There is no need to change anything in Web.config
If anyone looking for an equivalent of the accepted answer (Osman's) when working with dart web (webdev), here's what worked for me on Dart 2.17.6 (a bit more complex but in case you needed a quick fix, it might be handful).
Find webdev executable (this helps) then you see something like this:
The snapshot file (generated if not exist, as you see) is executed when you want to run app in browser. It contains the code that dart runs when launching chrome (using browser_launcher dart package).
Backup and remove the snapshot file (location in the screenshot above) so it can be regenerated in next run.
Locate browser_launcher package in your pub cache (also you might find location of browser_launcher by searching in the snapshot file) and edit lib\src\chrome.dart, find '--disable-extensions' and add '--disable-web-security'.
Run your app and remove the backup created in step 2.
If you are working with django in the side of the service, you can configure CORS with 'corsheaders', in this link you can find whole the documentation to setup your back end and recognice your requests.
https://pypi.org/project/django-cors-headers/
Go to flutter\bin\cache and remove a file named: flutter_tools.stamp
Go to flutter\packages\flutter_tools\lib\src\web and open the file chrome.dart.
Find '--disable-extensions'
Add '--disable-web-security'

Persits ASPPDF ImportFromUrl ServerXMLHTTP Error: The request has timed out

We have a test website that uses Persits ASPPDF to build a PDF using the ImportFromUrl method. It works fine on our test domain, but when I use the same code on another domain (and crucially perhaps, a sub-domain) I get the "MSXML2::ServerXMLHTTP Error: The request has timed out." error.
This leads me to think its related to the problem outlined in
https://support.persits.com/show.asp?code=PS080709171
"the calling Active Server Page (ASP) should not send requests to an ASP in the same virtual directory or to another virtual directory in the same pool or process. This can result in poor performance due to thread starvation."
So perhaps the config of the two servers hosting the two sites (test and live) are different - and if so what would that be? - Or you can't run this method on a sub-domain? Any guidance out there please?
I've had the same issue for weeks and finally found out what the problem was. In my case, it was because I had set to True the options that allow the debug of classic ASP code, without which I could not debug using visual studio. Setting those options back to False fixed the issue.

Sporadic invalid_request 400 errors connecting to Shopify /admin/oauth/access_token

I am using a java raw HTTP client to connect to Shopify API (specifically, using Play Framework with the non-defualt sync driver which is actually the JDK's default driver).
My application usually manages to connect successfully and convert the temporary access token into a permanent one by calling the /admin/oauth/access_token endpoint.
However, sometimes I get this error result from the API:
Generic Error(400)
{"error":"invalid_request"}
I haven't been able to reproduce the issue with my test stores - I've tried installing a fresh store, reinstalling existing stores after uninstalling, I'm not sure why this call sometimes fail and how to debug it. The API call still continues to succeed for some stores using our application.
Some things that I am doing:
Even if the URL of the store is on a custom domain, I'm always using the https://foo.myshopfiy.com/admin/oauth/access_token URL and not the URL of the custom domain, to prevent a redirect.
I am always using an https URL and never an http one, again to prevent a redirect (we noticed a few issues with redirect with the Java HTTP client, so we aim to have zero redirects)
A thread I found about this error suggest possible problems with our SSL certificates, however I don't think this is my problem because some requests work for us, and the result of running openssl on our machine does't show any issues.
How should I proceed? Open a support ticket with Shopify?
FYI, I see that this specific problem only started yesterday on Feb 19 2013, so it might be a temporary issue.
FYI, the problem was caused by reusing a temporary access code.
Our fault - Shopify could have been more clear in their error message though.

WCF Services not working from Silverlight Application after Deploying

Okay I have seen some very similar questions here but none seem to be answered to my liking. I have created a Silverlight application that calls a couple of services to populate various comboboxes from the database. I got this working without too much trouble on my local machine.
So now I want to deploy it to our webserver. It was relatively straight forward to get ISS7 to load the Silverlight application. However, none of my services seem to be working properly, in that the comboboxes are empty. In IE I get the following error:
Message: Unhandled Error in Silverlight Application An exception occurred during the operation, making the result invalid. Check InnerException for exception details. at System.ComponentModel.AsyncCompletedEventArgs.RaiseExceptionIfNecessary()
at MyTestPage.ViewModel.MyService.GetInfoCompletedEventArgs.get_Result()
at MyTestPage.ViewModel.MainPageViewModel.b__2(Object s, GetInfoCompletedEventArgs ea)
at MyTestPage.ViewModel.MyService.MyServiceClient.OnGetInfoCompleted(Object state)
Line: 1
Char: 1
Code: 0
URI: http://www.mywebsite.com/MyTestPage.aspx
My problem is that this error only occurs when deploying on the webserver and I have no clue how to debug this problem. The error says to check the InnerException but I haven't found an answer yet (after hours of searching) that tells me how I should do this.
I have tried browsing to the services and I am able to do so using the domain name i.e. http://test.myserver.com/Services/MyService.svc. However when logged onto the server and using http://localhost:3456/Services/MyService.svc - which is the path in the ServicesReferences.ClientConfig file - It cannot be found.
Some answers here seem to suggest using a clientaccesspolicy.xml file but I don't understand why this should be necessary if the services are hosted on the same server as the application - they aren't required when debugging on my local machine. Despite my reservations I have tried adding a clientaccesspolicy.xml file to the root of the application but this still doesn't make any difference.
So I have a couple of questions:
1) How do I get access to the InnerException when I am running the application on the webserver? Is there a specific log file I can view or turn on?
2) If, for some reason, I am trying to access the service in a cross domain fashion (even though they are located on the same server) how do I configure the application so that this isn't required?
UPDATE:
Ok, I was able to get the tracing to work. I can now see the trace details on the page when it loads but it doesn't really tell me anything useful. I have also added the option to write the details to the disk. Initially this file wasn't being written and I couldn't understand why. Then I noticed that refreshing my silverlight application was not triggering a write to the log. It was only when I manually browsed to the services that the log file was updated. This seems to indicate to me that my silverlight application is not hitting the services at all (for some reason). I tried cutting out the View Model object and hitting the service directly from the xaml code behind file but this didn't make any difference either.
At this point after spending more than two days trying to figure this out, I am thinking about starting again from scratch.
For my mind it shouldn't be this difficult to deploy something that works on a development machine to a webserver.
I pretty much gave up on my initial approach. I had another go following along from this video http://www.silverlight.net/learn/videos/all/net-ria-services-intro/. It uses Domain services instead of the WCF Services and it was actually fairly straight forward to get it going on the webserver. The example is two years old now so maybe there are better ways to do this now (I am open to suggestions) but at least it worked within an hour of trying it (compared to 2.5 days and getting nowhere).