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',
};

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);
    });
  };

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?

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

  • Unarc dll вернул код ошибки 1 как исправить error archive data corrupted
  • Unarc dll вернул код ошибки 1 error archive data corrupted decompression files
  • Unarc dll вернул код ошибки 1 dark souls
  • Unarc dii вернул код ошибки 12
  • Unarac dll вернул код ошибки 1