1

I'm new to the Phoenix framework, and I've been struggling for days to get my React frontend project to speak to my Phoenix JSON API. I generated the API code using one of the generators. I'm able to successfully make POST requests with an API tester (reqbin.com), but when I try to make a request with the same body from my page, I always get back a "400 Bad Request" response. It seems likely that this is do to some Header nuance I'm missing, but for the life of me I can't figure it out.

Here's my router code:

pipeline :api do
    plug :accepts, ["json"]
    plug CORSPlug, origin: "*"
  end

  scope "/api", HelloWeb do
    pipe_through :api

    get "/", PageController, :index

    get "/test", PageController, :test

    resources "/users", UserController

    resources "/apps", AppController

And my request code from my react app.

     var body = {app:{"name":"Phoenix_Test"}}
    console.log(body);
    var that = this;
    var schema = fetch(db_url_var, {
                method: 'POST',
                body: body,
                mode: 'no-cors',
                headers: {
                  'Content-Type': "application/json",
                  Accept: "application/json"
                }
      }).then(function(res){
        alert("Saved!")
         // that.setState({"hidden":true})
      })
  
  • 3
    What do your Phoenix logs say? I would recommend logging the _entire request_ struct in Phoenix and compare a successful request (e.g. made using Postman or similar tool) to the requests made by React. Firstly, that will ensure that the request is making it to your Phoenix instance, and secondly, that should enable you to compare the 2 requests to see what is different about them. – Everett Feb 15 '21 at 06:56
  • 1
    Never use no-cors mode. https://stackoverflow.com/a/43268098/441757 Drop the `mode: 'no-cors'` part from your fetch call. That won’t fix the 400 error but it will at least prevent the next problem you’d run into once you get the cause of the 400 error fixed. – sideshowbarker Feb 15 '21 at 06:57
  • Thanks @Everett. How do I log the request? I know its making it to my instance, because I see an auto-generated log saying that the endpoint has been hit. But I'm not sure how to log the request given that it needs to be done in the router -- its never making it to the controller -- and Im not sure how to log it before its rejected. – nadrojtayl27 Feb 15 '21 at 15:35

0 Answers0