{HELP ME} http: POST /api/orders (4 ms) 500 error

:wave:t2: hi there


I was making an address form for an e-commerce website. in which the user has to fill out the form to book an order. While writing the post method. i got this 500 error


the url also exist

here’s the code below!!

import React, { useState } from 'react';
import { makeStyles } from '@mui/styles';
import { TextField, Grid, Button } from '@mui/material';

const useStyles = makeStyles((theme) => ({
  formContainer: {
    margin: 'auto',
    padding: theme.spacing(3),
    maxWidth: '600px',
    backgroundColor: '#f7f7f7',
    borderRadius: '8px',
    boxShadow: '0 2px 4px rgba(0,0,0,0.12), 0 2px 4px rgba(0,0,0,0.24)',
    marginTop: theme.spacing(12),
  },
  textField: {
    marginBottom: theme.spacing(5),
  },
  button: {
    marginTop: theme.spacing(2),
  },
}));

const Form = () => {
  const classes = useStyles();
  const [fullName, setFullName] = useState('');
  const [addressLine1, setAddressLine1] = useState('');
  const [addressLine2, setAddressLine2] = useState('');
  const [city, setCity] = useState('');
  const [state, setState] = useState('');
  const [zipCode, setZipCode] = useState('');
  const [country, setCountry] = useState('');
  const [email, setEmail] = useState('');
  const [phone, setPhone] = useState('');

  const handleSubmit = (event) => {
    event.preventDefault();
    const data = {
      fullName,
      addressLine1,
      addressLine2,
      city,
      state,
      zipCode,
      country,
      email,
      phone,
    };
    fetch('http://localhost:1337/api/orders', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(data),
    })
      .then((response) => response.json())
      .then((data) => console.log(data))
      .catch((error) => console.error(error));
  };

  return (
    <form className={classes.formContainer} onSubmit={handleSubmit}>
      <Grid container spacing={2}>
        <Grid item xs={12}>
          <TextField
            className={classes.textField}
            fullWidth
            required
            id="full-name"
            label="Full Name"
            variant="outlined"
            value={fullName}
            onChange={(event) => setFullName(event.target.value)}
          />
        </Grid>
        <Grid item xs={12}>
          <TextField
            className={classes.textField}
            fullWidth
            required
            id="address-line1"
            label="Address Line 1"
            variant="outlined"
            value={addressLine1}
            onChange={(event) => setAddressLine1(event.target.value)}
          />
        </Grid>
        <Grid item xs={12}>
          <TextField
            className={classes.textField}
            fullWidth
            id="address-line2"
            label="Address Line 2"
            variant="outlined"
            value={addressLine2}
            onChange={(event) => setAddressLine2(event.target.value)}
          />
        </Grid>
        <Grid item xs={12} sm={6}>
          <TextField
            className={classes.textField}
            fullWidth
            required
            id="city"
            label="City"
            variant="outlined"
            value={city}
            onChange={(event) => setCity(event.target.value)}
          />
        </Grid>
               <Grid item xs={12} sm={6}>
          <TextField
            className={classes.textField}
            fullWidth
            required
            id="state"
            label="State/Province/Region"
            variant="outlined"
            value={state}
            onChange={(event) => setState(event.target.value)}
          />
        </Grid>
        <Grid item xs={12} sm={6}>
          <TextField
            className={classes.textField}
            fullWidth
            required
            id="zip-code"
            label="Zip/Postal Code"
            variant="outlined"
            value={zipCode}
            onChange={(event) => setZipCode(event.target.value)}
          />
        </Grid>
        <Grid item xs={12} sm={6}>
          <TextField
            className={classes.textField}
            fullWidth
            required
            id="country"
            label="Country"
            variant="outlined"
            value={country}
            onChange={(event) => setCountry(event.target.value)}
          />
        </Grid>
        <Grid item xs={12}>
          <TextField
            className={classes.textField}
            fullWidth
            required
            id="email"
            label="Email"
            variant="outlined"
            value={email}
            onChange={(event) => setEmail(event.target.value)}
          />
        </Grid>
        <Grid item xs={12}>
          <TextField
            className={classes.textField}
            fullWidth
            required
            id="phone"
            label="Phone Number"
            variant="outlined"
            value={phone}
            onChange={(event) => setPhone(event.target.value)}
          />
        </Grid>
        <Grid item xs={12}>
          <Button
            className={classes.button}
            variant="contained"
            color="primary"
            type="submit"
          >
            Place Order
          </Button>
        </Grid>
      </Grid>
    </form>
  );
};

export default Form;

***in order content type builder everything exists. ***

***Thank you, I hope that anyone will help me ***

What is the error you get in your strapi console (where strapi is running)
When you get 500 Error always check strapi console as that should tell you what crashed and what happened.
Also suggest maybe you post what the schema for orders as well so people might look or know what you are trying to do :slight_smile:

Did you check permsion in strapi admin panel, settings, roles → public/Auth ?

Hello @ramon_julia , I did check the permission roles in the settings and I also still get the same error. In my case, I am trying to create a new order using stripe payments. All I am getting is a 500 error from the server. Here are some of the logs:

[2023-03-31 05:16:12.922] http: POST /api/orders (1150 ms) 500
[2023-03-31 05:16:12.939] http: POST /api/orders (948 ms) 500
[2023-03-31 05:16:13.145] http: POST /api/orders (979 ms) 500
[2023-03-31 05:16:13.360] http: POST /api/orders (744 ms) 500

Could anyone explain to me what’s going on on the server side of things coz I have double-checked the permissions, refreshed my client app given it a try, and no success. All I get are the above results from the server log…Is there another way around this…?

Oh also @Eventyret Hello. I am new to strapi and I love using it. I am glad I found this forum where I can share ideas and problem-solve with like-minded individuals. I noticed you mentioned the schema for orders to be displayed so that further examination can be done, well since I already posted my server logs, let me post my schema for orders we figure out what’s actually going on.

const stripe = require(‘stripe’)(process.env.STRIPE_KEY);
‘use strict’;

/**

  • order controller
    */

const { createCoreController } = require(’@strapi/strapi’).factories;

module.exports = createCoreController(‘api::order.order’,({strapi})=>({
async create(ctx){
const{ products } = ctx.request.body;

     try {
        const lineItems = await Promise.all(  //we use promise all because we have more than one product
        products.map(async (product)=>{
          const item = await strapi
          .service('api::product.product')
          .findOne(product.id);
          return {
              price_data:{
                  currency:"usd",
                  product_data:{
                      name: item.title
                  },
                  unit_amount:Math.round(item.price*100),
              },
               quantity: item.quantity,
          }
        })
      
       );

     const session = await stripe.checkout.sessions.create({
        shipping_address:{allowed_countries:['US','AUS','KE','UK']},
        payment_method: ["card"],
        mode: 'payment',
        success_url: `${process.env.CLIENT_URL}?success=true`,
        cancel_url: `${process.env.CLIENT_URL}/?success=false`,
        line_items: lineItems,  
      });

      await strapi
      .service("api::order.order")
      .create({ data: {  products, stripeId: session.id } });

      return { stripeSession: session };
     } catch (error) {
        ctx.response.status = 500;
        return { error };
     }
      
  },

}));

Them If it is not permision, them what that happened to me is becouse soemthing in the process something is wrong. maybe go step by step in your order-controller, Today I have a error maping something that wasn’t array but object and give 500 error, Hope can give you a clue

BTW in you funtion? I think is strapi.entityService, intead of service?

okay @ramon_julia . Well, I tried changing the strapi.service to strapi.entityService but it still brings the same error. I am going through my order controller line by line now.Hopefully, some progress will happen through multiple tries at least.

@Cherrypick14 did you find the solution? I have exact same problem as you