Hi,
I've an api in production using iris.
I've this configuration.
func getCors() context.Handler {
crs := cors.New(cors.Options{
AllowedOrigins: []string{"*"},
AllowedMethods: []string{"GET", "HEAD", "POST", "PUT", "OPTIONS", "DELETE"},
AllowedHeaders: []string{"Accept", "content-type", "Access-Control-Allow-Origin", "X-Requested-With", "Content-Length", "Accept-Encoding", "X-CSRF-Token", "Authorization", "Screen", "token", "offset", "limit"},
AllowCredentials: true,
})
return crs
}
func initApp() {
app = iris.New()
app.Use(getCors())
}
In front using chrome or firefox I get an error doing this :
fetch(url, {
method: 'post',
body: JSON.stringify({"email": email}),
headers: {
'Content-Type': 'application/json',
}
})
The complete error :
Access to fetch at 'https://domain-name.com:8080/user/connect/' from origin 'http://10.18.206.202:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: Redirect is not allowed for a preflight request.
I allowed all origins in the cors configuration, tried using many IPs as sender (wifi IP, 127.0.0.1, localhost).
I also tried to add this in my initApp function :
app.UseGlobal(func(ctx iris.Context){
ctx.Header("Access-Control-Allow-Origin", "*")
ctx.Next()
})
What should I do to make it works?
Hello, you want help for a community-driven middleware from the iris-contrib/middleware repository, this is not the place for these things but the 1 line example tells you that you have to use the .AllowMethods("OPTIONS"), this is for the preflight request but I don't see that option at your code snippet, please try to add it and post here if that worked for you, thank you.
Hi,
Sorry for having posted that in the wrong place.
These are my routes
func (user *User) InitRoutes() {
userAPI := api.App.Party("/user").AllowMethods(iris.MethodPost).AllowMethods(iris.MethodGet).AllowMethods(iris.MethodPut).AllowMethods(iris.MethodDelete).AllowMethods(iris.MethodHead)
/* /user */
userAPI.Post("/", createUser)
userAPI.Post("/connectcode", connectCode)
userAPI.Post("/connect", connect)
userAPI.Head("/email/:email", isEmailExist)
userAPI.Get("/", CheckAndGetUserByToken, getUser)
userAPI.Put("/profil", CheckAndGetUserByToken, updateProfil)
userAPI.Put("/device", CheckAndGetUserByToken, updateDevice)
}
So even with this function it doesn't work.
Edit : I also use the last version of Iris.
Hi,
When you put .AllowMethods to a group of routes like this you will allow all these methods to passed for the routes that is part of that group, i.e userAPI.Post("connectcode", ...) will register for POST method but you are allowing it for GET, PUT, HEAD and DELETE (which I don't understand why). But anyway, again, the OPTIONS is missing from your code snippet.
Add .AllowMethods(iris.MethodOptions) to your userAPI.
Hi Kataras,
My bad, I misunderstood the function.
I add the .AllowMethods(iris.MethodOptions) and I get the same error.
here how it is now :
userAPI := api.App.Party("/user").AllowMethods(iris.MethodOptions)
Does it work for you ?
Hmmm yes it works here but it may be a js ajax request issue, but first please test that code snippet below, that worked for https://github.com/kataras/iris/issues/847#issuecomment-353771457
userAPI := api.App.Party("/user").AllowMethods(iris.MethodOptions)
userAPI .Use(func(ctx iris.Context){
ctx.Header("Vary", "Access-Control-Request-Method")
ctx.Header("Access-Control-Allow-Origin", "*")
ctx.Header("Access-Control-Request-Headers","Accept,content-type,X-Requested-With,Content-Length,Accept-Encoding,X-CSRF-Token,Authorization,token")
ctx.Header("Access-Control-Request-Method","*")
ctx.Next()
})
// [... your routes here]
If that ^ does not work for you then it is a javascript fetch issue, if you read the mozzila's documentation at: https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch#Supplying_request_options you will see that there is an option for cors, that is defaulted to "same-origin" you have to change it to "cors":
fetch(url, {
method: "POST", // *GET, POST, PUT, DELETE, etc.
mode: "cors", // other options: no-cors and same-origin which is the default
/ [...]
Thanks,
Gerasimos Maropoulos.
Hi Gerasimos,
Thank you for all your answers.
As you asked me I tried put the code you sent me in my user routes :
My Initialisation routes function looks like this :
func (user *User) InitRoutes() {
userAPI := api.App.Party("/user").AllowMethods(iris.MethodOptions)
userAPI.Use(func(ctx iris.Context) {
ctx.Header("Vary", "Access-Control-Request-Method")
ctx.Header("Access-Control-Allow-Origin", "*")
ctx.Header("Access-Control-Request-Headers", "Accept,content-type,X-Requested-With,Content-Length,Accept-Encoding,X-CSRF-Token,Authorization,token")
ctx.Header("Access-Control-Request-Method", "*")
ctx.Next()
})
/* /user */
userAPI.Post("/", createUser)
userAPI.Post("/connectcode", connectCode)
userAPI.Post("/connect", connect)
userAPI.Head("/email/:email", isEmailExist)
userAPI.Get("/", CheckAndGetUserByToken, getUser)
userAPI.Put("/profil", CheckAndGetUserByToken, updateProfil)
userAPI.Put("/device", CheckAndGetUserByToken, updateDevice)
userAPI.Put("/picture", CheckAndGetUserByToken, updateProfilPicture)
}
I got the same error on the last version of chrome and firefox.
So I updated my fetch function to define the mode as cors.
Like this :
fetch(url, {
headers: {
"Content-Type": "application/json",
'Access-Control-Allow-Origin': '*'
},
method: "POST",
mode: 'cors',
body: JSON.stringify({ email: email }),
});
And still the same result, this error :

So I changed many parameters in the fetch function, trying also with axios, and still same error.
Actually the only way I found to received the request on the server was in setting the mode as no-cors.
In 2017 I used iris in back with reactjs in front, the same way I'm using it right now and it worked, I can't see what I changed.
I'll try tomorrow with a nodeJS server to check if it works.
Thank you,
Fantasim
Hi,
So as I said in the previous message, I tried with an express server with nodeJS and it works.
If you want to see my very basic express server :
import express from 'express'
import { format } from 'url';
var app = express();
var allowCrossDomain = function(req, res, next) {
console.log('AH?')
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Access-Control-Allow-Origin");
res.header("Access-Control-Allow-Origin", "*");
next();
}
app.use(allowCrossDomain);
app.post('/user/connectcode', function (req, res) {
console.log("Got a POST request");
res.send('Hello POST');
})
var server = app.listen(8081, function () {
var host = server.address().address
var port = server.address().port
console.log("App listening at http://%s:%s", host, port)
})
I'm out of ideas to make it works with iris :/
Framework does not matter for headers and cors, just copy-paste carefully, without trailing spaces after commas and it will work, here you are:
crs := func(ctx iris.Context) {
ctx.Header("Access-Control-Allow-Origin", "*")
ctx.Header("Access-Control-Allow-Credentials", "true")
ctx.Header("Access-Control-Allow-Headers", "Access-Control-Allow-Origin,Content-Type")
ctx.Next()
}
userAPI := api.App.Party("/user", crs).AllowMethods(iris.MethodOptions)
// [...]

Hi,
No It still doesn't work.
I even tried to start a new little iris project with a simple post request, that I installed on a distant server.
package main
import (
"fmt"
"github.com/kataras/iris"
)
func post(ctx iris.Context) {
fmt.Println("It works.")
}
func main() {
app := iris.New()
crs := func(ctx iris.Context) {
ctx.Header("Access-Control-Allow-Origin", "*")
ctx.Header("Access-Control-Allow-Credentials", "true")
ctx.Header("Access-Control-Allow-Headers", "Access-Control-Allow-Origin,Content-Type")
ctx.Next()
}
v1 := app.Party("/v1", crs).AllowMethods(iris.MethodOptions)
{
v1.Post("/", post)
}
app.Run(iris.Addr(":8082"))
}
URL for the request : http://185.212.227.66:8082/v1/ if you want to try.
PS : Last year I used to use iris V6, so i tried to downgrade iris to use it with one of my old project.
So I used exactly the same fetch request (without the "Access-Control-Allow-Origin", in header) and it works.
@Fantasim , do you want to join to our chat https://chat.iris-go.com and talk with me private (I need access to that url) to find out a solution? When we find a decent solution, and we will, we will push the solution down to the repository, sounds ok with you?
@kataras Send me a message when you are free, I'm on the chat with the same username than github.
I think you are calling wrong port.
@kataras has fixed the problem, it was a path problem :
If one day you meet the problem just use this option : here