Axios put request with path variable

Viewed 693

I am trying to make a PUT request with Axios to update a Profile schema I have. I am able to update the Profile Schema with Postman as seen below but when I use axios I am getting a network error. Any insight on how I can fix this issue would be much appreciated!!!

enter image description here

Here's the body of PUT request in Postman as well...enter image description here

Finally, here is the code where I make the axios PUT request

axios
  .put(
    `http://localhost:3000/api/profiles/${id}`,
    {
      bio: "updating bio!!!!",
      friends: null,
      postHistory: null,
      list: null,
      profilePic: "this is my new image link",
    },
    {
      headers: {
        Authorization: `token ${token}`,
      },
    }
  )
  .then((response) => {
    console.log(response);
    console.log("modified a user profile successfully");
  })
  .catch((error) => {
    console.log(error);
    console.log("error in modifying a user profile");
  });

I am currently getting a Network Error, with the exact error shown below

Network Error
at node_modules/axios/lib/core/createError.js:16:14 in createError
at node_modules/axios/lib/adapters/xhr.js:117:24 in handleError
at node_modules/react-native/Libraries/Network/XMLHttpRequest.js:609:10 in setReadyState
at node_modules/react-native/Libraries/Network/XMLHttpRequest.js:396:6 in __didCompleteResponse
at node_modules/react-native/Libraries/vendor/emitter/_EventEmitter.js:135:10 in EventEmitter#emit

When I do the command

curl -X PUT -v "http://localhost:3000/api/profiles/{6233c8393ea07b03841ea787}"

the output is

*   Trying 127.0.0.1:3000...
* Connected to localhost (127.0.0.1) port 3000 (#0)
> PUT /api/profiles/6233c8393ea07b03841ea787 HTTP/1.1
> Host: localhost:3000
> User-Agent: curl/7.78.0
> Accept: */*
> 
* Mark bundle as not supporting multiuse
< HTTP/1.1 401 Unauthorized
< Access-Control-Allow-Origin: *
< Content-Security-Policy: default-src 'self';base-uri 'self';block-all-mixed-content;font-src 'self' https: data:;form-action 'self';frame-ancestors 'self';img-src 'self' data:;object-src 'none';script-src 'self';script-src-attr 'none';style-src 'self' https: 'unsafe-inline';upgrade-insecure-requests
< Cross-Origin-Embedder-Policy: require-corp
< Cross-Origin-Opener-Policy: same-origin
< Cross-Origin-Resource-Policy: same-origin
< X-DNS-Prefetch-Control: off
< Expect-CT: max-age=0
< X-Frame-Options: SAMEORIGIN
< Strict-Transport-Security: max-age=15552000; includeSubDomains
< X-Download-Options: noopen
< X-Content-Type-Options: nosniff
< Origin-Agent-Cluster: ?1
< X-Permitted-Cross-Domain-Policies: none
< Referrer-Policy: no-referrer
< X-XSS-Protection: 0
< Content-Type: application/json; charset=utf-8
< Content-Length: 57
< ETag: W/"39-ZOIs/1GD8EVMpSJwxt0l7LYxxZY"
< Date: Fri, 18 Mar 2022 02:44:22 GMT
< Connection: keep-alive
< Keep-Alive: timeout=5
< 
* Connection #0 to host localhost left intact

When adding the command

console.error(error.toJSON())

the corresponding output is

Object {
  "code": undefined,
  "columnNumber": undefined,
  "config": Object {
    "adapter": [Function xhrAdapter],
    "data": "{\"bio\":\"updating bio!!!!\",\"friends\":[],\"postHistory\":[],\"list\":[],\"profilePic\":\"this is my new image link\"}",
    "headers": Object {
      "Accept": "application/json, text/plain, */*",
      "Authorization": "token eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiI2MjMzYzgzOTNlYTA3YjAzODQxZWE3ODQiLCJ1c2VybmFtZSI6IkplbGxvIiwicm9sZSI6IkNMSUVOVCIsImlhdCI6MTY0NzU3MDc4MiwiZXhwIjoxNjQ3NzQzNTgyfQ.zfNaxmamPF_agsuITm3Z9jPSMCtIBpH9fsZhvZ30-Xs",
      "Content-Type": "application/json",
    },
    "maxBodyLength": -1,
    "maxContentLength": -1,
    "method": "put",
    "timeout": 0,
    "transformRequest": Array [
      [Function transformRequest],
    ],
    "transformResponse": Array [
      [Function transformResponse],
    ],
    "transitional": Object {
      "clarifyTimeoutError": false,
      "forcedJSONParsing": true,
      "silentJSONParsing": true,
    },
    "url": "http://localhost:3000/api/profiles/6233c8393ea07b03841ea787",
    "validateStatus": [Function validateStatus],
    "xsrfCookieName": "XSRF-TOKEN",
    "xsrfHeaderName": "X-XSRF-TOKEN",
  },
  "description": undefined,
  "fileName": undefined,
  "lineNumber": undefined,
  "message": "Network Error",
  "name": "Error",
  "number": undefined,
  "stack": "createError@http://10.203.251.235:19000/node_modules/expo/AppEntry.bundle?platform=ios&dev=true&hot=false&strict=false&minify=false:118636:26
handleError@http://10.203.251.235:19000/node_modules/expo/AppEntry.bundle?platform=ios&dev=true&hot=false&strict=false&minify=false:118539:27
dispatchEvent@http://10.203.251.235:19000/node_modules/expo/AppEntry.bundle?platform=ios&dev=true&hot=false&strict=false&minify=false:35194:31
setReadyState@http://10.203.251.235:19000/node_modules/expo/AppEntry.bundle?platform=ios&dev=true&hot=false&strict=false&minify=false:34326:33
__didCompleteResponse@http://10.203.251.235:19000/node_modules/expo/AppEntry.bundle?platform=ios&dev=true&hot=false&strict=false&minify=false:34134:29
emit@http://10.203.251.235:19000/node_modules/expo/AppEntry.bundle?platform=ios&dev=true&hot=false&strict=false&minify=false:2841:42
__callFunction@http://10.203.251.235:19000/node_modules/expo/AppEntry.bundle?platform=ios&dev=true&hot=false&strict=false&minify=false:3678:36
http://10.203.251.235:19000/node_modules/expo/AppEntry.bundle?platform=ios&dev=true&hot=false&strict=false&minify=false:3406:31
__guard@http://10.203.251.235:19000/node_modules/expo/AppEntry.bundle?platform=ios&dev=true&hot=false&strict=false&minify=false:3632:15
callFunctionReturnFlushedQueue@http://10.203.251.235:19000/node_modules/expo/AppEntry.bundle?platform=ios&dev=true&hot=false&strict=false&minify=false:3405:21
callFunctionReturnFlushedQueue@[native code]",
  "status": null,
}

In addition, my package.json file looks like this:

{
  "name": "jellyclient",
  "version": "1.0.0",
  "main": "node_modules/expo/AppEntry.js",
  "scripts": {
    "start": "expo start",
    "android": "expo start --android",
    "ios": "expo start --ios",
    "web": "expo start --web",
    "eject": "expo eject"
  },
  "dependencies": {
    "@react-navigation/bottom-tabs": "^6.2.0",
    "@react-navigation/native": "^6.0.8",
    "@react-navigation/native-stack": "^6.5.0",
    "axios": "^0.26.0",
    "expo": "~44.0.0",
    "expo-image-picker": "~12.0.1",
    "expo-status-bar": "~1.2.0",
    "expo-updates": "~0.11.6",
    "ionicons": "^6.0.1",
    "mongoose": "^6.2.2",
    "native-base": "^3.3.7",
    "react": "17.0.1",
    "react-dom": "17.0.1",
    "react-native": "0.64.3",
    "react-native-dotenv": "^3.3.1",
    "react-native-fast-image": "^8.5.11",
    "react-native-feather": "^1.1.2",
    "react-native-safe-area-context": "3.3.2",
    "react-native-screens": "~3.10.1",
    "react-native-svg": "^12.1.1",
    "react-native-unordered-list": "^1.0.4",
    "react-native-web": "0.17.1",
    "react-navigation-stack": "^2.10.4",
    "validator": "^13.7.0"
  },
  "devDependencies": {
    "@babel/core": "^7.12.9"
  },
  "private": true
}

2 Answers

Notice that you are sending Authorization token as token ${token}. Usually prefix is the bearer and not token.

axios({
  method: 'put',
  url: `http://localhost:3000/api/profiles/${id}`,
  data: {
    bio: "updating bio!!!!",
    friends: null,
    postHistory: null,
    list: null,
    profilePic: "this is my new image link",
  },
  headers: {
    Authorization: `bearer ${token}`,
  },
});

Alright after doing some research I believe you might have a broken hosts file and/or network lookup...
For example if you try your axios put request with

http://127.0.0.1:3000/api/profiles/${id}

I bet you would find it works with the same setup you have (calling 127.0.0.1 instead of localhost). This is because localhost isn't inherently your local machine however the hosts file generally points it to your machine (127.0.0.1).
Further I would like to point out that Postman automatically converts localhost to 127.0.0.1 behind the scenes, thus why it works so well.
Give this a try and if it doesn't work attempt to change it to 0.0.0.0:3000 as this would indicate an odd port binding...

Related