I have an my app configured to use grunt-connect-proxy. Request reach the server and evverything is working fine apart from POST requests.
When running grunt with the verbose option set, I can see:
Proxied request: /api/data.json -> http://myProdutionDomain.com:80/beta/api/data.json
{
"host": "0.0.0.0:9000",
"connection": "keep-alive",
"content-length": "15",
"accept": "application/json, text/plain, */*",
"origin": "http://0.0.0.0:9000",
"user-agent": "Mozilla/5.0 (Macintosh; ...)",
"content-type": "application/json;charset=UTF-8",
"referer": "http://0.0.0.0:9000/",
"accept-encoding": "gzip,deflate,sdch",
"accept-language": "en",
"cookie": "some-cookie",
}
My proxies configuration is as follows:
proxies: [
{
context: '/api',
host: 'myProdutionDomain.com',
changeOrigin: true,
rewrite: {
'^/': '/beta/'
}
}
]
From Angular I just do:
$http.post(requestUrl, {'id': id});
Also tried:
request = $http.post(requestUrl, {'id': id}, {'headers': {'Content-Type': 'application/x-www-form-urlencoded'}});
Problem is the 'id' post param is never sent to the server.
Anyone has experience with this?
Related
I have a REST API with symfony/api-plateform on port 8000 and front app React on port 3000
In my React App: I want to get file with url
let url = 'http://localhost:8000/delivrables/school/2021/b1_cpd/homework_matiere_0__devoir_0/picard-%C3%89lisabeth.zip'
axios.get(url)
.then(res => {
console.log(res)
})
but I get a CORS error :
Access to XMLHttpRequest at 'http://localhost:8000/delivrables/school/2021/b1_cpd/homework_matiere_0__devoir_0/picard-%C3%89lisabeth.zip' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
react_devtools_backend.js:4049
I have configurated my app symfony/api-plateform for cors :
CORS_ALLOW_ORIGIN=^https?://.*?$
When I call this URL (for exemple) with postman (http://localhost:8000/delivrables/school/2021/b1_cpd/homework_matiere_0__devoir_0/picard-%C3%89lisabeth.zip) that work.
Try with header (not work) :
axios(url, {
method: 'GET',
headers: {
'Access-Control-Allow-Origin': '*',
}
}).then(response => {
console.log(response)
})
nelmio_cors.yml
nelmio_cors:
defaults:
origin_regex: true
allow_origin: ['*']
allow_methods: ['GET', 'OPTIONS', 'POST', 'PUT', 'PATCH', 'DELETE']
allow_headers: ['Content-Type', 'Authorization']
expose_headers: ['Link']
max_age: 3600
hosts: []
paths:
'^/':
origin_regex: true
allow_origin: ['%env(CORS_ALLOW_ORIGIN)%']
allow_methods: ['GET', 'OPTIONS', 'POST', 'PUT', 'PATCH', 'DELETE']
allow_headers: ['X-Custom-Auth']
max_age: 3600
hosts: ['^api\.']
You can try adding this to your React project's package.json
"proxy": "http://localhost:8000"
But of course this will work just for this dev server setup, not for production.
And also in this case you should use "relative" url in your request, that is starting with /delivrables...
I have a react application with server side rendering using Express server . I want to make a POST request using axios but it is getting blocked with CORS error :
"Access to XMLHttpRequest at 'https://xyz/abc' from origin 'http://localhost:4249' 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.
I have tried after adding allow origin headers and cors module in my server call but that didn't work
import cors from "cors";
const server = express();
server.use((req, res, next) => {
res.header("Access-Control-Allow-Origin", "*");
res.header(
"Access-Control-Allow-Methods",
"OPTIONS, GET, POST, PUT, PATCH, DELETE"
);
res.header("Access-Control-Allow-Headers", "Content-Type, Authorization");
next();
});
server.use(express.static("dist"));
server.use(cors());
Here is the axios request :
const headers = {
Accept: "application/json",
"x-ms-version": "2019-07-11",
Authorization: token,
"x-ms-date": date,
"x-ms-documentdb-isquery": true,
"Content-Type": "application/query+json",
"x-ms-documentdb-query-enablecrosspartition": "true",
"cache-control": "no-cache",
"Access-Control-Allow-Origin": "*",
};
useEffect(() => {
axios
.post(
"https://xyz/abc",
data,
{
headers: headers,
}
)
.then(function (response) {
setres(response.data);
})
.catch(function (error) {
console.log(error);
});
}, []);
Webpack Config:
module.exports = {
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: "babel-loader",
},
},
{
test: /\.(sass|css|scss)$/,
use: ["style-loader", "css-loader"],
},
],
},
};
I have encountered this problem before, and this is just what I did:
app.js (backend)
server.use(cors({
origin: '<YOUR_FRONTEND_URL_PATH>',
methods: 'GET,HEAD,POST,PUT,DELETE',
preflightContinue: false,
credentials: true
}));
axios request:
const resp = await axios.post(
apiUrl,
params,
{
withCredentials: true,
timeout: 10000
}
);
Hello so I am trying to upload images to AWS S3 from my React application using an NPM package called react-s3. I am using an AWS Educate account and have setup the access and secret key correctly. After I select the image and console log the output it gives me a 403 forbidden error as follows.
POST https://shopkartimages.s3.amazonaws.com/ 403 (Forbidden)
Response {type: "cors",
url: "https://shopkartimages.s3.amazonaws.com/",
redirected: false,
status: 403, ok:
false, …}
body: (...)
bodyUsed: false
headers: Headers
__proto__: Headers
ok: false
redirected: false
status: 403
statusText: "Forbidden"
type: "cors"
url: "https://shopkartimages.s3.amazonaws.com/"
__proto__: Response
My bucket policy is as follows :
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "S3Permissions",
"Effect": "Allow",
"Principal": "*",
"Action": [
"s3:Get*",
"s3:List*"
],
"Resource": "arn:aws:s3:::shopkartimages/*"
}
]
}
My CORS configuration in S3 is as follows:
[
{
"AllowedHeaders": [
"*"
],
"AllowedMethods": [
"PUT",
"POST",
"DELETE"
],
"AllowedOrigins": [
"*"
],
"ExposeHeaders": [
"x-amz-server-side-encryption",
"x-amz-request-id",
"x-amz-id-2"
],
"MaxAgeSeconds": 3000
}
]
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "S3Permissions",
"Effect": "Allow",
"Principal": "*",
"Action": [
"s3:Get*",
"s3:List*"
],
"Resource": "arn:aws:s3:::shopkartimages/*"
}
]
}
Your bucket policy only allow Get & List operations.
And uploading a file is a PUT operation.
I ran into this exact same problem with react-s3. I finally abandoned it in favor of AWS SDK which works fine for me (even in react). Here's what it took.
First install aws-sdk:
$ npm install aws-sdk
Then replace whatever you were doing with react-s3 with this:
import AWS from 'aws-sdk';
AWS.config.update({ region:region, credentials: new AWS.Credentials(secret_id, secret_access_key)});
var s3 = new AWS.S3({apiVersion: "2006-03-01", params: { Bucket: bucketName }});
let upload_params = {Bucket: bucketName, Key: file.path, Body: file};
let upload = new AWS.S3.ManagedUpload({params: upload_params});
let promise = upload.promise();
promise.then(
function(data){console.log("Successfully uploaded:", file.path);},
function(err){console.log("Failed to upload", file.name, "with error:", err.message);}
);
Here's my CORS stuff from S3 Bucket Permissions:
[
{
"AllowedHeaders": [
"*"
],
"AllowedMethods": [
"HEAD",
"GET",
"PUT",
"POST",
"DELETE"
],
"AllowedOrigins": [
"*"
],
"ExposeHeaders": [
"ETag"
]
}
]
Also, public access is blocked and I'm not messing around with custom bucket policies.
Hope this helps someone else dealing with these CORS/S3/react nightmares.
I have a Spring Boot app as a back-end API and a React app as a front end.
CORS is enabled in the Spring Boot and I use axios to send requests to the Spring Boot API.
When calling '/login', Spring Boot security kicks in and produces a JWT
token, which is passed back to ReactJS as the Authorization header. The
issue is that this header does not appear in the response received in the
React app then processing block. It does show correctly in the Developer
Tools Network tab. Below is the relevant code:
axios.post("http://localhost:8080/login", LoginRequest)
.then(response => {console.log("RRR ", response)});
The console output is as follows:
{data: "", status: 200, statusText: "", headers: {…}, config: {…}, …}
config:
adapter: ƒ xhrAdapter(config)
data: "{"username":"test#test.com","password":"test$2"}"
headers:
Accept: "application/json, text/plain, */*"
Content-Type: "application/json;charset=utf-8"
__proto__: Object
maxContentLength: -1
method: "post"
timeout: 0
transformRequest: {0: ƒ}
transformResponse: {0: ƒ}
url: "http://localhost:8080/login"
validateStatus: ƒ validateStatus(status)
xsrfCookieName: "XSRF-TOKEN"
xsrfHeaderName: "X-XSRF-TOKEN"
__proto__: Object
data: ""
headers: {pragma: "no-cache", cache-control: "no-cache, no-store, max-age=0, must-revalidate", expires: "0"}
request: XMLHttpRequest {onreadystatechange: ƒ, readyState: 4, timeout: 0, withCredentials: false, upload: XMLHttpRequestUpload, …}
status: 200
statusText: ""
What am I missing?
I am working with a yeoman generator-angular app and a remote API, my gruntfile config seems to be fine:
// Generated on 2015-06-01 using generator-angular 0.11.1
'use strict';
module.exports = function (grunt) {
/ * Removed for brevity */
grunt.initConfig({
yeoman: appConfig,
watch: {
/ * Removed for brevity */
},
connect: {
options: {
port: 9000,
hostname: 'localhost',
livereload: 35729
},
proxies: [
{
context: '/api',
host: 'subdomain.hostname.com',
xforward: true,
secure: false,
headers: {
'Authorization': 'RemovedToken'
},
}
],
livereload: {
options: {
open: true,
middleware: function (connect, options) {
var middlewares = [require('grunt-connect-proxy/lib/utils').proxyRequest];
middlewares.push(
connect.static('.tmp'),
connect().use('/bower_components',connect.static('./bower_components')),
connect().use('/app/styles', connect.static('./app/styles')),
connect().use(connect.static(appConfig.app))
);
return middlewares;
}
}
},
/ * Removed for brevity */
},
/ * Removed for brevity */
});
grunt.registerTask('serve', 'Compile then start a connect web server', function (target) {
if (target === 'dist') {
return grunt.task.run(['build', 'connect:dist:keepalive']);
}
grunt.task.run([
'clean:server',
'wiredep',
'concurrent:server',
'autoprefixer:server',
'configureProxies:server',
'connect:livereload',
'watch'
]);
});
grunt.loadNpmTasks('grunt-connect-proxy');
};
grunt serve --verbose returns this when a request is made:
Proxied request: /api/foo/bar/?baz=6 -> http://subdomain.hostname.com:80/api/foo/bar/?baz=6
{
"host": "localhost:9000",
"connection": "keep-alive",
"accept": "application/json, text/plain, */*",
"user-agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.124 Safari/537.36",
"referer": "http://localhost:9000/",
"accept-encoding": "gzip, deflate, sdch",
"accept-language": "en-US,en;q=0.8,es;q=0.6",
"cookie": "connect.sid=s%3AQpOp8pdI8GM2g8s0qCX602-ds-Xs-5le.C%2BrosIxHQ4ZcLLPgZKhABjji18kqK2K73C7mjF6scqM",
"Authorization": "RemovedToken",
"x-forwarded-for": "127.0.0.1",
"x-forwarded-port": "9000",
"x-forwarded-proto": "http"
}
I can't find any error there, maybe that the "host" is still localhost:9000, but I'm unsure if that could be a problem and in Chrome I am getting: 503 Service Unavailable, but there is indeed a service running, I know because I tested it with Postman and everything works fine, could somebody help me with this? Maybe I am missing something in the configuration?
Thanks.
After digging some more in the project I found that I had to specify the "host" header too.
https://github.com/drewzboto/grunt-connect-proxy/issues/72