0

Im trying to make a post request with one parameter in AJAX to a local server. When I execute the request in postman it seems to work perfectly fine but when I do it with AJAX it sends over two requests one as a 204 and another one as a 404 which seems very strange:

<-- OPTIONS /price/current
api_1       |   --> OPTIONS /price/current 204 1ms 
api_1       |   <-- POST /price/current
api_1       |   --> POST /price/current 404 1ms -

The actual AJAX request is the following:

getBtc = async()  => {
     return await fetch("http://localhost:3001/price/current",{
         method: 'POST',
         headers: {
             'Content-Type':'application/json'

         },
         body: JSON.stringify({
             'symbol':'eth'
         })
     })          
     .then(res => {
         console.log(res)
         if (res.success) {
           this.setState({ priceBTC : res.data[0].price })
         }
     })

The console log specifies a 200 response with te following info:

Response {type: "cors", url: "http://localhost:3001/price/btc", redirected: false, status: 200, ok: true, …}
body: (...)
bodyUsed: false
headers: Headers {}
ok: true
redirected: false
status: 200
statusText: "OK"
type: "cors"
url: "http://localhost:3001/price/btc"
__proto__: Response

Ideally I would be getting back a status code of 200

  • Any console output? – Emanuele Scarabattoli Jul 27 '19 at 22:54
  • Are you sure that the method is POST and not GET? – Emanuele Scarabattoli Jul 27 '19 at 22:56
  • Its a get in the server, modifying it breaks the endpoint though. –  Jul 27 '19 at 23:00
  • So you should use `method: 'GET'`, no? – Emanuele Scarabattoli Jul 27 '19 at 23:04
  • Getting the two responses isn't necessarily weird. That `options` response is just to verify what you are able to do. Does it require any credentials to be passed or a specific format for the body? – GenericUser Jul 27 '19 at 23:09
  • I haven't used postman much but I know that sometimes transforms aren't transparent. For instance ajax automatically transforms POST data objects into query strings. Is there any possibility that postman may be doing something similar? – GenericUser Jul 27 '19 at 23:12
  • You need to implement CORS headers as an OPTIONS request won't get sent unless origin is different (port, protocol, domain etc). Rest clients like Postman are not cors restricted the way browsers are – charlietfl Jul 28 '19 at 00:23
  • changed everything to a get in the server and sacrificed some flexibility. but Im having this issue now, check edit of the post. –  Jul 28 '19 at 00:43

1 Answers1

0

Please try this:

.then(res => res.json())
.then(jsonRes => {
    console.log(jsonRes)
    if (jsonRes.success) {
        this.setState({ priceBTC : jsonRes.data[0].price })
    }
 })
.catch(err => {
    alert('Something went wrong')
});

Here we are converting the response res into json and from that we're accessing the data[]

pasanjg
  • 566
  • 5
  • 13