Uncaught in promise ошибка 404

If your are using laravel for API and vue/Nuxtjs for frontend and axios for send data to API….
This type of errors can be faced for laravel validation error sending not in correct way using try{} catch(){} block or receiving errors by axios not in correct way to using try() catch(){} block.
Here, try catch block using for error handling.

If your API routes called the public function its name «register()», so your function inside your controller have to like following…(I am using laravel-8 for API)

public function register(Request $request) {
    try {
        $fields = $request->validate([
            'name' => 'required|string',
            'email' => 'required|string|email|unique:users',
            'password' => 'required|string|confirmed',
        ]);

        $user = User::create([
            'name' => $fields['name'],
            'email' => $fields['email'],
            'password' => bcrypt($fields['password'])
        ]);
        
        $token = $user->createToken('myapptoken')->plainTextToken;
        $response = [
            'user' => $user,
            'token' => $token,
        ];
        
        return response()->json($response, 200);
    } catch(ValidationException $e) {            
        return response()->json([
            'status' => 'error',
            'msg' => 'error',
            'errors' => $e->errors()
        ], 422);
    }
}

and Frontend Nuxt or vue methods name is «registerNewUser()» so, codes can be following for error handling…

async registerNewUser() {
    try {
      let data = {
        name             : this.name.trim(),
        email            : this.email.trim(),
        password         : this.password.trim(),
        password_confirmation : this.password_confirmation.trim(),
      };
      let headers = {
        headers: {
            'Accept': 'application/json',
        }
      };
      await this.$axios
      .post("/api/register", data, headers)
      .then((response) => {
        console.log("response", response);
        if(response) {
          // console.log(response)
        } else {

        }
      });
    } catch(err) {
      // here we are receiving validation errors
      console.log("Err == ", err.response);
      console.log(err.response.data.errors);
    }
}

You are receiving response inside axios then block or receive error inside catch block using err.response

Here,

let data = {
   name             : this.name.trim(),
   email            : this.email.trim(),
   password         : this.password.trim(),
   password_confirmation : this.password_confirmation.trim(),
};

Given codes is for data of Nuxtjs or vuejs. If not know that you can using like following data or any other data…

let data = {
   name             : 'Kallol',
   email            : 'kallolray94@gmail.com',
   password         : '123456',
   password_confirmation : '123456',
};

Description

I find sometimes when pressing the back button, then from there clicking on another link, nothing happens. I see this in the console: app-fe7c17e2944200c5b471.34096c386004d3b05de6e33102e6278b.js:1 Uncaught (in promise) Error: 404 page could not be found. Checkout https://www.gatsbyjs.org/docs/add-404-page/ at app-fe7c17e2944200c5b471.34096c386004d3b05de6e33102e6278b.js:1.

Steps to reproduce

  1. go to https://www.fgbg.art
  2. click on a link, then a thumbnail to arrive at a detail page
  3. press back button to return to list page
  4. click on another thumbnail

Expected result

goes to other detail page

Actual result

error in console as noted above.

Environment

System:
OS: Linux 4.15 Ubuntu 18.04.3 LTS (Bionic Beaver)
CPU: (8) x64 Intel(R) Core(TM) i7-7700K CPU @ 4.20GHz
Shell: 4.4.20 — /bin/bash
Binaries:
Node: 10.16.0 — ~/.nvm/versions/node/v10.16.0/bin/node
Yarn: 1.12.3 — ~/.yarn/bin/yarn
npm: 6.9.0 — ~/.nvm/versions/node/v10.16.0/bin/npm
Languages:
Python: 2.7.15+ — /usr/bin/python
Browsers:
Chrome: 76.0.3809.100
Firefox: 68.0.1
npmPackages:
gatsby: ^2.13.20 => 2.13.20
gatsby-plugin-favicon: ^3.1.6 => 3.1.6
gatsby-plugin-google-analytics: ^2.1.4 => 2.1.4
gatsby-plugin-manifest: ^2.2.3 => 2.2.3
gatsby-plugin-offline: ^2.2.4 => 2.2.4
gatsby-plugin-react-helmet: ^3.1.2 => 3.1.2
gatsby-plugin-sharp: ^2.2.7 => 2.2.7
gatsby-plugin-typescript: ^2.1.2 => 2.1.2
gatsby-source-filesystem: ^2.1.5 => 2.1.5
gatsby-source-google-sheets: ^1.1.1 => 1.1.1
gatsby-transformer-csv: ^2.1.2 => 2.1.2
gatsby-transformer-sharp: ^2.2.3 => 2.2.3

More context

I think this only happens if I have the site loaded in my browser, and I deploy a new version.

The site is hosted on gh-pages, and thus I had the other problem of stale page-data.json files being used, so I employed the hack of adding a sha to basically all non-html files as described here. Here is the terrible code I wrote to do this.

If I refresh the page, everything works again as expected.

I suspect if I took the above sha hack out, this problem would go away. But then I’d be back to the stale page-data.json problem. I’m far from a gatsby expert, but it feels like being stuck between a rock and a hard place when using gh-pages. Maybe gatsby really is intended to be used in situations when you have control over the headers the server sets on responses?

Question: Uncaught (in Promise) Error: Request Failed With Status Code 404

Answer : 1

If You Get This Error Message It Means That Your Error Handling-code Isn’t There Or That It Could Not Be Reached, Therefore The Promise Was Unhandled (since The Catch-part Of Your Wasn’t Properly Setup).,Generally This Error Comes When The Url/location Provided Inside GET Method Is Not Correct.
So Check The Url/location Again And Correct It.,I Am Getting Above Error While Fetching Some Data From The API. Following Is The Code Of The Action Creator Where I Am Trying GET The Data:

In My Case It Was A Minor Syntax Error (a Misplacement Of My Brackets).
My Code Looked Like This:

axiosget("/api-url").then(
  (response)  => {
    DoSomething();
  }), ()  => {
  DoError();
  }
);

instead Of This:

axiosget("/api-url").then(
  (response)  => {
    DoSomething();
  }, () =>  {
  DoError();
  });
);

If Your API Routes Called The Public Function Its Name «register()», So Your Function Inside Your Controller Have To Like Following…(I Am Using Laravel-8 For API)

public Function Register(Request  $request) {
    Try {
        $fields =  $request->validate([
             'name' => 'required|string',
             'email' =>  'required|string|email|unique:users',
             'password' =>  'required|string|confirmed',
         ]);

        $user = User::create([
             'name' => $fields['name'],
             'email' => $fields['email'],
             'password' =>  Bcrypt($fields['password'])
        ]);
         
        $token =  $user->createToken('myapptoken')->plainTextToken;
         $response = [
            'user'  => $user,
            'token' =>  $token,
        ];
        
         Return Response()->json($response,  200);
    } Catch(ValidationException  $e) {            
        Return  Response()->json([
             'status' => 'error',
             'msg' => 'error',
             'errors' => $e->errors()
         ], 422);
    }
}

and Frontend Nuxt Or Vue Methods Name Is «registerNewUser()» So, Codes Can Be Following For Error Handling…

async RegisterNewUser() {
    Try {
       Let Data = {
        Name             :  This.name.trim(),
        Email             : This.email.trim(),
        Password          : This.password.trim(),
         Password_confirmation :  This.password_confirmation.trim(),
       };
      Let Headers = {
         Headers: {
            'Accept':  'application/json',
        }
      };
       Await This.$axios
       .post("/api/register", Data, Headers)
       .then((response) => {
         Console.log("response", Response);
         If(response) {
          //  Console.log(response)
        } Else {

         }
      });
    } Catch(err) {
       // Here We Are Receiving Validation  Errors
      Console.log("Err == ",  Err.response);
       Console.log(err.response.data.errors);
     }
}

Here,

let Data = {
   Name             :  This.name.trim(),
   Email            :  This.email.trim(),
   Password         :  This.password.trim(),
    Password_confirmation :  This.password_confirmation.trim(),
};

Given Codes Is For Data Of Nuxtjs Or Vuejs. If Not Know That You Can Using Like Following Data Or Any Other Data…

let Data = {
   Name             :  'Kallol',
   Email            :  '[email protected]',
   Password          : '123456',
   Password_confirmation  : '123456',
};

Answer : 2

See More Details

  ANYCODING SOLVED THIS ISSUE 

Answer : 3

Send The Same Request By Curl Or Other Libraries Without Axios,Compare Request Headers Between To Local With To Remote Server,It Is A Problem That The Server Can’t Response Correctly, Instead Of An Issue Of Axios. Before Closing, I Want To Give You Some Directions And Hope They Can Help You. You Can Look For More Help In Stackoverflow.

ANYCODINGS

curl

Answer : 4

Generally This Error Comes When The Url/location Provided Inside GET Method Is Not Correct. So Check The Url/location Again And Correct It.,Also When I Am Debugging In The Code Editor, Console Is Giving Me Below Error:,I Am Getting Above Error While Fetching Some Data From The API. Following Is The Code Of The action Creator where I Am Trying GET the Data:

I Am Getting Above Error While Fetching Some Data From The API. Following Is The Code Of The action Creator where I Am Trying GET the Data:

import { FETCH_USER } From  './types';
Import Axios From  'axios';


Export Const FetchUser = ()  => Async Dispatch => {

         Console.log('fetchUser');

        Const  Res= Await  Axios.get('/api/current_user');

         Dispatch({ Type: FETCH_USER, Payload:  Res });

}; 

Answer : 5

See More Details

  ANYCODING SOLVED THIS ISSUE 

Answer : 6

Now The Promise That Is Created In The GetUsers() Function Returns The Following Error: ERROR: Error: «Request Failed With Status Code 404»,@dollique Said In Axios: Request Failed With Status Code 404:,The 404 Error Means Axios Couldn’t Get The Resource That It Requested. That Error Is From The Server Though. So, It Sounds Like Axios Connects With Your Server I.e. Your Server Receives The Request. However, Your Server Isn’t Finding The Resource Being Requested. So, I Think You’ll Need To Trouble Shoot Your Server Set Up.

As This Tutorial Is Based Open Native VueJS And Not Quasar I Tried To Apply This To The Framework.
What I Did Is I Changed The /boot/axios.js To The Following:

import Vue From 'vue'
Import Axios From  'axios'

Vue.prototype.$axios =  Axios

Export Default () => {
   Return Axios.create({
    BaseURL:  `http://localhost:8081/` // The Url Of  Our Server
  })
}

I Then Created The File UsersAPI.js In The Folder /boot.

import Axios From  '../boot/axios'

Export Default {
   GetUsers () {
    // Console.log('GET  USERS', Axios().get('users'))
    Var  UsersPromise = Axios().get('users')
     UsersPromise.then(function (result) {
       Console.log('RESULT', Result)
       Return Result
    })
       .catch(function (err) {
         Console.log('ERROR: ', Err)
      })
   }
}

Last But Not Least My Code In The Vue Page:


  
    
      
        This Is A Box.
         
          Data:
          
             {{ User.name }}
          
         
      
      
        This Is A Box
       
    
    
      
        
      
     
  



Import UsersAPI From  '../boot/usersAPI.js'

Export Default {
   Name: 'PageIndex',
  Data () {
     Return {
      DataReady: False,
       Users: []
    }
  },
  Mounted () {
     This.loadUsers()
  },
  Methods: {
     Async LoadUsers () {
      Const  Response = Await UsersAPI.getUsers()
       This.users = Response.data

       This.dataReady = True
    }
  }
}

axios.js

import Vue From 'vue'
Import Axios From  'axios'

Const AxiosInstance =  Axios.create({
  BaseURL:  `http://localhost:8081/` // The Url Of  Our Server
})

Vue.prototype.$axios =  AxiosInstance

Export { AxiosInstance }

usersAPI.js

import { AxiosInstance } From  '../boot/axios'

Export Default {
   GetUsers: Async () => {
    Var  UsersPromise =  AxiosInstance.get('users')
    Return  UsersPromise
  }
}

I Want To Filter My Results By The Name Of The User, So I Implemented Params Like This:

import { AxiosInstance } From  '../boot/axios'

Export Default {
   GetUsers: Async (userName) => {
     Var UsersPromise =  AxiosInstance.get('users', {
       Params: {
        Name: 'test'
      }
     })
    Return UsersPromise
  }
}

This Is Ignored Somehow So I Tried To Also Change The Backend To The Following:

app.get('/users', (req, Res) => {
   Const Collection =  Client.db("MYDB").collection("users")

   Collection.find(req.query.name).toArray(function  (err, Results) {
    If (err) {
       Console.log(err)
      Res.send([])
       Return
    }
    Res.send(results)
   })
})

Answer : 7

See More Details

  ANYCODING SOLVED THIS ISSUE 

Answer : 8

Hi Anyone, I Am Using Nuxtjs For My Project. But I Have A Problem, On Mode Ssr(server Side Render) When Run Project Is Axios Throw Error Request Failed With Status Code 404:
,Powered By Discourse, Best Viewed With JavaScript Enabled,Thanks Anyone, I Was Resolve This Problem. Because I Config Url Of Api Is » //domainapi.com» When On Web Browser Can Running Normal But On Nodejs Server In Can’t Running With “//domain” Instead Have To Edit Is “http://domain”

import Axios From "axios";
Export Class  ApiConnect {
  Constructor({ Commit,  Key_commit }) {
    This.commit = Commit  ? Commit : Null;
    This.key_commit =  Key_commit ? Key_commit : Null;
  }
  
   Async Get(url) {
    Console.time(url);
     Await Axios
      .get(url)
       .then(response => {
        If  (response.data.status != 200) {
           Throw "404";
        }
         This.commit(this.key_commit, { Data:  Response.data.data });
         Console.timeEnd(url);
      })
       .catch(error => {
         Console.log("api Error:" + Error);
         Throw Error;
      });
  }
}

Answer : 9

You Would Need To Check The Error Log To Understand What Happens . An Error 500 Means That The Server Throw An Exception From Which It Could Not Recover.,Where The Error_log Is Will Depend On Your Project Configuration. It May Be In /var/log/apache/error_log (if You Connect Through SSH To Homestead).,It Seems That Laravel.log Contains All The Relevant Information.
Searching Through The File For “error”, I Found This:


    
        Follow
    



    Export  Default {

        Props:['userId'],

         Mounted() {
             Console.log('Component Mounted.')
         },

        Methods: {
             FollowUser() {

                     Axios.post('/follow/' + This.userId)
                 .then(response => {
                     Alert(response.data);
                 });

                }
             }

    }
Route::post('/follow/{user}',  '[email protected]');
[2020-09-08 15:12:12] Local.ERROR:  Target Class [AppHttpControllersUser]  Does Not Exist.  {"userId":3,"exception":"[object]  (Illuminate\Contracts\Container\BindingResolutionException(code:  0): Target Class  [App\Http\Controllers\User] Does Not  Exist. At  C:\cmder\freeCodeGram\vendor\laravel\framework\src\Illuminate\Container\Container.php:811)
[stacktrace]
use AppUser;

Answer : 10

I Am Attempting To Integrate The YouTube API Into A New Vuejs Application And I Am Testing It In The Browser And Continuing To Get A 404 Error. ,I Did Have A Www Missing, But I Continue To Get This Same Error When I Make The Request. Is There Something I Am Not Seeing In My Code That Is Wrong? Is It A Cors Issue? If So, What Is The Standard Practice For Resolving This In Vuejs? I Have Made A Similar Application In Reactjs And Did Not Run Into This Issue.,What I Would Suggest Is To Add A Catch To Your Call To Handle Errors In The Future.


  
    
  



Import Axios From  "axios";
Import SearchBar From  "./components/SearchBar";
Const API_KEY  = "";

Export Default {
  Name: "App",
   Components: {
    SearchBar
  },
   Methods: {
    OnTermChange(searchTerm)  {
      Axios
         .get("https://www.googleapis.com/youtube/v3/search",  {
          Params: {
            Keys:  API_KEY,
            Type: "video",
             Part: "snippet",
            Q:  SearchTerm
          }
        })
         .then(response =>  Console.log(response));
    }
  }
};

"code": 403,
  "message": "Daily Limit  For Unauthenticated Use Exceeded.  Continued Use Requires Signup."
 }
}
axios
   .get("https://www.googleapis.com/youtube/v3/search",  {
    Params: {
      Keys: API_KEY,
       Type: "video",
      Part: "snippet",
       Q: SearchTerm
    }
  })
   .then(response =>  Console.log(response));
  .catch(err  => { Console.log(err); }

Answer : 11

See More Details

  ANYCODING SOLVED THIS ISSUE 

Solution 1

Generally this error comes when the url/location provided inside GET method is not correct.
So check the url/location again and correct it.

So most probably there is some mistake here : ‘/api/current_user’

Solution 2

In my case it was a minor syntax error (a misplacement of my brackets).
My code looked like this:

axiosget("/api-url").then(
  (response) => {
    doSomething();
  }), () => {
  doError();
  }
);

instead of this:

axiosget("/api-url").then(
  (response) => {
    doSomething();
  }, () => {
  doError();
  });
);

If you get this error message it means that your error handling-code isn’t there or that it could not be reached, therefore the promise was unhandled (since the catch-part of your wasn’t properly setup).

If you get this message always doublecheck your syntax!

Comments

  • I am getting above error while fetching some data from the API. Following is the code of the action creator where I am trying GET the data:

    import { FETCH_USER } from './types';
    import axios from 'axios';
    
    
    export const fetchUser = () => async dispatch => {
    
            console.log('fetchUser');
    
            const res= await axios.get('/api/current_user');
    
            dispatch({ type: FETCH_USER, payload: res });
    
    }; 
    

    Also when I am debugging in the code editor, console is giving me below error:

    SyntaxError: Unexpected token import

Recents

I need to send data to backend, but I am having this error:

Uncaught (in promise) Error: Request failed with status code 404

How can I solve this??

Image below:

error

Code javascript below:

handleClick(_success, _error) {
    const usuarioLogin = this.props.cliente;
    const usuarioCliente = parseInt(this.state.usuario);

    const ObjetoChamado = {
      titulo: this.state.titulo,
      descricao: this.state.descricao,
      area: parseInt(this.state.area),
      categoria: parseInt(this.state.categoria),
      servico: parseInt(this.state.servico),
      usuario: usuarioLogin,
      cliente: usuarioCliente,
    };

    this.props.abrirChamado(
      ObjetoChamado,
      (response) => {
        this.props.getChamados(usuarioLogin, null, (chamados) => {
          // Chamado aberto, atualizar lista e fechar o popup de abertura
          this.props.setClientData(usuarioLogin, null, chamados.data.objeto);
          this.props.visible(false);
        });
      },
      (error) => {
        alert(!!error ? error : 'Não foi possível abrir o chamado.');
      }
    );

    axios.post(ObjetoChamado).then((response) => {
      const data = response.data;

      //   if (Object.keys(data).length > 0) {
      //     if (typeof _success === 'function') _success(data);
      //   } else {
      //     if (typeof _error === 'function') {
      //       _error({
      //         code: 404,
      //         message: 'Não há nenhum registro para este cliente.',
      //       });
      //     }
      //   }
      console.log('DATA:', data);
    });
  };

If your are using laravel for API and vue/Nuxtjs for frontend and axios for send data to API….
This type of errors can be faced for laravel validation error sending not in correct way using try{} catch(){} block or receiving errors by axios not in correct way to using try() catch(){} block.
Here, try catch block using for error handling.

If your API routes called the public function its name «register()», so your function inside your controller have to like following…(I am using laravel-8 for API)

public function register(Request $request) {
    try {
        $fields = $request->validate([
            'name' => 'required|string',
            'email' => 'required|string|email|unique:users',
            'password' => 'required|string|confirmed',
        ]);

        $user = User::create([
            'name' => $fields['name'],
            'email' => $fields['email'],
            'password' => bcrypt($fields['password'])
        ]);
        
        $token = $user->createToken('myapptoken')->plainTextToken;
        $response = [
            'user' => $user,
            'token' => $token,
        ];
        
        return response()->json($response, 200);
    } catch(ValidationException $e) {            
        return response()->json([
            'status' => 'error',
            'msg' => 'error',
            'errors' => $e->errors()
        ], 422);
    }
}

and Frontend Nuxt or vue methods name is «registerNewUser()» so, codes can be following for error handling…

async registerNewUser() {
    try {
      let data = {
        name             : this.name.trim(),
        email            : this.email.trim(),
        password         : this.password.trim(),
        password_confirmation : this.password_confirmation.trim(),
      };
      let headers = {
        headers: {
            'Accept': 'application/json',
        }
      };
      await this.$axios
      .post("/api/register", data, headers)
      .then((response) => {
        console.log("response", response);
        if(response) {
          // console.log(response)
        } else {

        }
      });
    } catch(err) {
      // here we are receiving validation errors
      console.log("Err == ", err.response);
      console.log(err.response.data.errors);
    }
}

You are receiving response inside axios then block or receive error inside catch block using err.response

Here,

let data = {
   name             : this.name.trim(),
   email            : this.email.trim(),
   password         : this.password.trim(),
   password_confirmation : this.password_confirmation.trim(),
};

Given codes is for data of Nuxtjs or vuejs. If not know that you can using like following data or any other data…

let data = {
   name             : 'Kallol',
   email            : 'kallolray94@gmail.com',
   password         : '123456',
   password_confirmation : '123456',
};

Description

I find sometimes when pressing the back button, then from there clicking on another link, nothing happens. I see this in the console: app-fe7c17e2944200c5b471.34096c386004d3b05de6e33102e6278b.js:1 Uncaught (in promise) Error: 404 page could not be found. Checkout https://www.gatsbyjs.org/docs/add-404-page/ at app-fe7c17e2944200c5b471.34096c386004d3b05de6e33102e6278b.js:1.

Steps to reproduce

  1. go to https://www.fgbg.art
  2. click on a link, then a thumbnail to arrive at a detail page
  3. press back button to return to list page
  4. click on another thumbnail

Expected result

goes to other detail page

Actual result

error in console as noted above.

Environment

System:
OS: Linux 4.15 Ubuntu 18.04.3 LTS (Bionic Beaver)
CPU: (8) x64 Intel(R) Core(TM) i7-7700K CPU @ 4.20GHz
Shell: 4.4.20 — /bin/bash
Binaries:
Node: 10.16.0 — ~/.nvm/versions/node/v10.16.0/bin/node
Yarn: 1.12.3 — ~/.yarn/bin/yarn
npm: 6.9.0 — ~/.nvm/versions/node/v10.16.0/bin/npm
Languages:
Python: 2.7.15+ — /usr/bin/python
Browsers:
Chrome: 76.0.3809.100
Firefox: 68.0.1
npmPackages:
gatsby: ^2.13.20 => 2.13.20
gatsby-plugin-favicon: ^3.1.6 => 3.1.6
gatsby-plugin-google-analytics: ^2.1.4 => 2.1.4
gatsby-plugin-manifest: ^2.2.3 => 2.2.3
gatsby-plugin-offline: ^2.2.4 => 2.2.4
gatsby-plugin-react-helmet: ^3.1.2 => 3.1.2
gatsby-plugin-sharp: ^2.2.7 => 2.2.7
gatsby-plugin-typescript: ^2.1.2 => 2.1.2
gatsby-source-filesystem: ^2.1.5 => 2.1.5
gatsby-source-google-sheets: ^1.1.1 => 1.1.1
gatsby-transformer-csv: ^2.1.2 => 2.1.2
gatsby-transformer-sharp: ^2.2.3 => 2.2.3

More context

I think this only happens if I have the site loaded in my browser, and I deploy a new version.

The site is hosted on gh-pages, and thus I had the other problem of stale page-data.json files being used, so I employed the hack of adding a sha to basically all non-html files as described here. Here is the terrible code I wrote to do this.

If I refresh the page, everything works again as expected.

I suspect if I took the above sha hack out, this problem would go away. But then I’d be back to the stale page-data.json problem. I’m far from a gatsby expert, but it feels like being stuck between a rock and a hard place when using gh-pages. Maybe gatsby really is intended to be used in situations when you have control over the headers the server sets on responses?

I’m trying to send data to my backend using axios but whenever I click the button I get these errors in the console: `xhr.js:178 POST http://localhost:8081/api/favourite/addToFavourite 404 (Not Found)` and

createError.js:16 Uncaught (in promise) Error: Request failed with status code 404

at createError (createError.js:16:1)

at settle (settle.js:17:1)

at XMLHttpRequest.handleLoad (xhr.js:61:1)

I’ve gone through the code and I don’t see any error with how my urls are written and they all seem to match up so I don’t understand why url is returning as invalid.

Edit: here’s a link to the stackoverflow question incase the formatting here is a bit difficult to read https://stackoverflow.com/questions/71563608/uncaught-in-promise-error-request-failed-with-status-code-404-why-is-it-inva

Here’s my server.js file

    const express = require("express");
    const cors = require("cors");
    const dbConfig = require("./app/config/db.config");
    
    const app = express();
    
    var corsOptions = {
      origin: "http://localhost:8081"
    };
    
    app.use(cors(corsOptions));
    
    // parse requests of content-type - application/json
    app.use(express.json());
    
    // parse requests of content-type - application/x-www-form-urlencoded
    app.use(express.urlencoded({ extended: true }));
    
    const db = require("./app/models");
    const Role = db.role;
    
    db.mongoose
      .connect(`mongodb+srv://tami00:MEUxClWqUNbLz359@cluster0.gmvao.mongodb.net/test?retryWrites=true&w=majority`, {
        useNewUrlParser: true,
        useUnifiedTopology: true
      })
      .then(() => {
        console.log("Successfully connect to MongoDB.");
        initial();
      })
      .catch(err => {
        console.error("Connection error", err);
        process.exit();
      });
    
    // simple route
    app.use('/api/favourite', require('./app/routes/favourite.routes'));
    // routes
    // require(".app/routes/favourite.routes")(app);
    require("./app/routes/auth.routes")(app);
    require("./app/routes/user.routes")(app);
    
    // set port, listen for requests
    const PORT = process.env.PORT || 8080;
    app.listen(PORT, () => {
      console.log(`Server is running on port ${PORT}.`);
    });
    
    function initial() {
      Role.estimatedDocumentCount((err, count) => {
        if (!err && count === 0) {
          new Role({
            name: "user"
          }).save(err => {
            if (err) {
              console.log("error", err);
            }
    
            console.log("added 'user' to roles collection");
          });
    
          new Role({
            name: "creator"
          }).save(err => {
            if (err) {
              console.log("error", err);
            }
    
            console.log("added 'creator' to roles collection");
          });
    
          new Role({
            name: "watcher"
          }).save(err => {
            if (err) {
              console.log("error", err);
            }
    
            console.log("added 'watcher' to roles collection");
          });
        }
      });
    }

This is the component file for favourites

    import Axios from 'axios';
    import React, { useEffect, useState } from 'react'
    import styled from "styled-components";
    
    const FavouriteButton = styled.button`
      height: 30px;
      width: 40px;
    `;
    
    function FavouriteComp(props) {
    
        const [favouriteNumber, setFavouriteNumber] = useState(0);
        const [favourited, setFavourited] =  useState(false);
    
        const variable = {
            userFrom: props.userFrom,
            movieId: props.movieInfo?.id,
            movieTitle: props.movieInfo?.title,
            movieImg: props.movieInfo?.poster_path
        }
        
        useEffect(() => {
    
            Axios.post('/api/favourite/favouriteNumber', variable)
            .then(response => {
                if(response.data.success){
                    setFavouriteNumber(response.data.favouriteNumber)
                }else {
                    alert('Failed to get number');
                }
            })
    
            Axios.post('/api/favourite/favourited', variable) 
                .then(response =>{
                    if(response.data.success){
                        setFavourited(response.data.favourited)
                    }else {
                        alert('Failed to get info');
                    }
                })
    
        }, [])
    
        const onClickFavourite = () => {
            if(favourited) {
                Axios.post('/api/favourite/removeFavorite', variable)
                    .then(response =>{
                        if(response.data.success){
                            setFavouriteNumber(favouriteNumber - 1)
                            setFavourited(!favourited)
                        }else {
                            alert('Failed to remove');
                        }
                    })
    
            }else {
                Axios.post('/api/favourite/addToFavourite', variable)
                    .then(response =>{
                        if(response.data.success){
                            setFavouriteNumber(favouriteNumber + 1)
                            setFavourited(!favourited)
                        }else {
                            alert('Failed to add');
                        }
                    })
            }
        }
    
    
        return (
            <div>
                <FavouriteButton onClick={onClickFavourite}>{favourited? "removed" : "add"}{favouriteNumber}</FavouriteButton>
            </div>
        )
    }
    
    export default FavouriteComp

Here is my backend routes for favourite

    const express =  require('express');
    const router = express.Router();
    const { authJwt } = require("../middlewares");
    
    router.post("/favouriteNumber", [authJwt.verifyToken], (req, res) => {
        Favourite.find({"movieId": req.body.movieId})
            .exec((err, favourite) => {
                if(err) return res.status(400).send(err)
                res.status(200).json({success: true, favouriteNumber: favourite.length})
            })
    })
    
    router.post("/favourited", [authJwt.verifyToken], (req, res) => {
        Favourite.find({"movieId": req.body.movieId, "userFrom": req.body.userFrom})
            .exec((err, favourite) => {
                if(err) return res.status(400).send(err) 
    
                let result = false;
                if(favourite.length !== 0) {
                    result = true
                }
    
                res.status(200).json({success: true, favourited: result});
    
    
            })
    })
    
    router.post("/addToFavourite", [authJwt.verifyToken], (req, res) => {
        
        const favourite = new Favourite(req.body)
    
        favourite.save((err, doc) => {
            if(err) return res.json({success: false, err})
            return res.status(200).json({success: true, doc})
        })
    })
    
    router.post("/removeFavorite", [authJwt.verifyToken], (req, res) => {
        
        Favourite.findOneAndDelete({movieId: req.body.movieId, userFrom: req.body.userFrom})
            .exec((err, doc) => {
                if(err) return res.json({success: false, err})
                return res.status(200).json({success: true, doc})
            })
    })
    
    module.exports = router;

#api #promise #axios #http-status-code-404

Вопрос:

Я пытался создать приложение погоды, но у меня возникли некоторые проблемы с проверкой статуса http в случае, если пользователь добровольно вставляет название города, которого не существует, или в случае, если пользователь допустит опечатку в поле ввода.

Единственная проблема в том, что я не могу найти способ вставить статус !== 200 в обещание axios.

Статус 200 работает довольно хорошо, но 404-нет. Я уверен, что где-то в обещании есть ошибка, но мне не удается найти выход из нее.

Более того, когда я регистрирую ошибку в консоли, она показывает это сообщение:

ошибка в консоли.журнал

 Uncaught (in promise) Error: Request failed with status code 404  at e.exports (createError.js:16)  at e.exports (settle.js:17)  at XMLHttpRequest.E (xhr.js:66)  

Язык JavaScript

 try{   axios.get(`https://api.openweathermap.org/data/2.5/weather?q=${city}amp;appid=${api_key}`).then(    async response =gt; {    let data = await response.data   if (response.status !== 200) {    throw new Error(response.status);    } else {    console.log(data)  document.getElementById('hum').textContent = data.main.humidity;  document.getElementById('feels-like').textContent = data.main.feels_like;  }}  )    } catch(error) {  if (response.status === 404) {  console.log(`Err: ${error}`);  throw err;  }      };   

Любые предложения действительно приветствуются. Спасибо!

Ответ №1:

Вы try/catch не поймаете отклонение, которое вы бросаете в свой .then() обработчик, и не поймаете никаких отклонений, которые axios он сам бросает, если вы await не вызовете axios.

 try {  await axios.get(...).then(...) } catch(e) {  // now you can catch a rejection }  

Или, конечно, вы могли бы вместо этого переключиться на использование .catch() .


Стилистически не рекомендуется смешивать try/catch , await и .then() здесь. Вы должны либо сделать:

 try {  const response = await axios.get(...);  // process response here, including throw } catch(e) {  // here you can catch a rejection, either from axios  // directly or from throwing in the processing }  

или:

 axios.get(...).then(...).catch(...)  

Комментарии:

1. Большое спасибо. Ошибка заключалась в обещании. Теперь это работает.

2. @Mark88 — Поскольку похоже, что вы здесь новичок, если это ответ на ваш вопрос, вы можете указать на это сообществу, нажав галочку слева от ответа. Это также принесет вам несколько очков репутации за соблюдение надлежащей процедуры здесь.

  • #1

Hello everybody!
I am a novice in ASP.NET and try to write my first application, whose client-size which is written in React.js, using this technology . This is the simple SPA, which should send the data from its form and getting respomse. But every request ends up with the message («Uncaught (in promise) Error: Request failed with status code 404») and I can’t resolve this problem.

Here is my FormComponent code:

import './Form.css'
import React, { Component } from 'react'
import axios from 'axios'

export default class Form extends Component {
  
    constructor(props){
        super(props)

        this.state={
            name: "",
            email: "",
            text: ""
        }

        this.onNameChange = this.onNameChange.bind(this);
        this.onEmailChange = this.onEmailChange.bind(this);
        this.onTextChange = this.onTextChange.bind(this);
        this.onSubmit = this.onSubmit.bind(this);
    }

    onNameChange(e) {
        this.setState({ name: e.target.value });
    }

    onEmailChange(e) {
        this.setState({ email: e.target.value });
    }

    onTextChange(e) {
        this.setState({ text: e.target.value });
    }

    onSubmit(e) {
        e.preventDefault();
        var commentName = this.state.name;
        var commentEmail = this.state.email;
        var commentText = this.state.text;
        if (!commentName || !commentEmail || !commentText) {
            return;
        }

        var data = new FormData(e.target);

        axios({
            method: 'post',
            url: '/',
            data: data,
        })
            .then((res) => {
                console.log(res);
            })
            .catch((err) => { throw err });

        this.setState({ name: "", email: "", text: "" });
      
    }

    render() {
        return (
            <section>
                <form id="my-form" onSubmit={this.onSubmit}>
                    <a id="feedback-btn" type="submit">Нам важлива ваша думка</a>
                    <label htmlFor="in_name">Ім'я:</label>
                    <input id="in_name" type="text" onChange={this.onNameChange}/>
                    <label htmlFor="in_email">Email:</label>
                    <input id="in_email" type="email" onChange={this.onEmailChange}></input>
                    <label htmlFor="text_feedback">Коментар:</label>
                    <textarea name="feedback" id="text_feedback" onChange={this.onTextChange}></textarea>
                    <button type="submit">Залиште відгук</button>
                </form>
            </section>
        )
    }
}

Controller API:

using Gazda.Models;
using Microsoft.AspNetCore.Mvc;
using System;

// For more information on enabling Web API for empty projects, visit [URL='https://go.microsoft.com/fwlink/?LinkID=397860']Part 3, add a view to an ASP.NET Core MVC app[/URL]

namespace Gazda.Controllers
{
    [Route("[controller]")]
    [ApiController]
    public class CommentController : ControllerBase
    {

        // POST api/<CommentController>
        [HttpPost]
        public IActionResult Post(Comment comment)
        {

            comment.Id = Guid.NewGuid().ToString();

            return Ok(comment);
        }

    }
}

And Comment Model:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Gazda.Models
{
    public class Comment
    {
        public string Id { get; set; }
        public string Name { get; set; }
        public string Email { get; set; }
        public string Text { get; set; }
    }
}

I can’t get, what I’m doing wrong. It seems to me it is very simple mistake, but I spendfor it a few hours and couldnt find any solution. Thanl you in advance!!!!
P.S. Sorry for my English

JohnH

  • #2

I fixed the post for readability by using code boxes like this:

insertcode.png

Skydiver

  • #4

Set a breakpoint on your Controller’s Post method. Is it even being reached?

Can PostMan or Swagger reach your Post method?

Skydiver

  • #5

axios({ method: 'post', url: '/', data: data, })

The URL looks suspicious to me. Most ASP.NET WebAPI method URLs look something like «/api/<controller>/<method>/». So your URL should at least be «/api/Comment»

  • #6

The URL looks suspicious to me. Most ASP.NET WebAPI method URLs look something like «/api/<controller>/<method>/». So your URL should at least be «/api/Comment»

Thank you so much. I changed URL and also passes information through dataForm.append(). Thanks to this I started to get a response from controller. But there the next problem appears: controller returns Comment object, which fields are null, except Id. What can be the reason of this problem?

Modified Form.js:

import './Form.css'
import React, { Component } from 'react'
import axios from 'axios'

export default class Form extends Component {
    
    constructor(props){
        super(props)

        this.state={
            name: "",
            email: "",
            text: ""
        }

        this.onNameChange = this.onNameChange.bind(this);
        this.onEmailChange = this.onEmailChange.bind(this);
        this.onTextChange = this.onTextChange.bind(this);
        this.onSubmit = this.onSubmit.bind(this);
    }

    onNameChange(e) {
        this.setState({ name: e.target.value });
    }

    onEmailChange(e) {
        this.setState({ email: e.target.value });
    }

    onTextChange(e) {
        this.setState({ text: e.target.value });
    }

    onSubmit(e) {
        e.preventDefault();
        var commentName = this.state.name;
        var commentEmail = this.state.email;
        var commentText = this.state.text;
        if (!commentName || !commentEmail || !commentText) {
            return;
        }

        console.log(commentName);
        console.log(commentEmail);
        console.log(commentText);

        var data = new FormData();

        data.append("name", commentName);
        data.append("email", commentEmail);
        data.append("text", commentText);
        axios({
            method: 'post',
            url: '/api/Comment',
            data: data,
        })
            .then((res) => {
                console.log(res.data);
            })
            .catch((err) => { throw err });

        this.setState({ name: "", email: "", text: "" });
        
    }

    render() {
        return (
            <section>
                <form id="my-form" onSubmit={this.onSubmit}>
                    <a id="feedback-btn" type="submit">Нам важлива ваша думка</a>
                    <label htmlFor="in_name">Ім'я:</label>
                    <input id="in_name" type="text" onChange={this.onNameChange}/>
                    <label htmlFor="in_email">Email:</label>
                    <input id="in_email" type="email" onChange={this.onEmailChange}></input>
                    <label htmlFor="text_feedback">Коментар:</label>
                    <textarea name="feedback" id="text_feedback" onChange={this.onTextChange}></textarea>
                    <button type="submit">Залиште відгук</button>
                </form>
            </section>
        )
    }
}

Modified CommentController:

[HttpPost]
        public IActionResult Post([FromQuery]Comment comment)
        {

            comment.Id = Guid.NewGuid().ToString();

            return Ok(comment);
        }

Skydiver

  • #7

Considering that you only set the Id in your controller method, why are you surprised?

Also, C# is case sensitive. It looks like your JavaScript is sending form data with lowercase field names, while your Comment class has Pascal case field names.

Dear ladies and gentlemen,

I receive following error after deployment of the SPFx solution to SharePoint 2019 App catalog:

«Uncaught (in promise) Error: Error making HttpClient request in queryable [404] Not Found»

When I run the solution through «gulp serve» everything works well. No errors occur.

In methods which use the «sp» object from «pnp» the error occured.

Here is one example:

import {sp} from ‘@pnp/sp’;

public GetListExistsAndContainsItems(listTitle: string): Promise<boolean> {

return new Promise<boolean>(async(resolve, reject) => {

if (listTitle) {

console.log(«GetListExistsAndContainsItems — listTitle: » + listTitle);

let listExists: boolean = false;

await sp.web.lists.getByTitle(listTitle).items.select(«Id»).getAll().then((allItems: any[]) => {

if (allItems) {

listExists = true;

console.log(«GetListExistsAndContainsItems — listExists: » + listExists);

resolve(listExists);
}
}).catch((error: any) => {

console.log(«GetListExistsAndContainsItems — error: » + error);

reject(error);
})
}
})
}

Classic rest api calls through the WebPartContext work well also after deployment of the solution into the app catalog.

Only calls through «sp» from «pnp» throw this error only after deployment to app catalog in SharePoint 2019.

Thank you for your help.

Ladislav Stupak

Понравилась статья? Поделить с друзьями:
  • Uncar dll вернул код ошибки
  • Unb ошибка на стиральной машине leran
  • Unb ошибка на стиральной машине hisense
  • Unarc all вернул код ошибки 12
  • Unarac dll вернул код ошибки 1