8000 POST request with x-www-form-urlencoded is failing as Bad Request · Issue #466 · unjs/ofetch · GitHub
[go: up one dir, main page]
More Web Proxy on the site http://driver.im/
Skip to content
POST request with x-www-form-urlencoded is failing as Bad Request #466
Open
@ssahillppatell

Description

@ssahillppatell

Environment

bun: 1.1.38
node: 18.17.0
ofetch: 1.4.1

Reproduction

I have a simple api that accepts a name and return a json response.
Steps:

  1. GO api to handle the request
package main

import (
	"encoding/json"
	"fmt"
	"log"
	"net/http"
)

func main() {
	http.HandleFunc("/hello", helloHandler)
	fmt.Println("Server is running on port 8080...")
	log.Fatal(http.ListenAndServe(":8080", nil))
}

func helloHandler(w http.ResponseWriter, r *http.Request) {
	if r.Method != http.MethodPost {
		http.Error(w, "Invalid request method", http.StatusMethodNotAllowed)
		return
	}

	err := r.ParseForm()
	if err != nil {
		http.Error(w, "Unable to parse form data", http.StatusBadRequest)
		return
	}

	name := r.FormValue("name")
	if name == "" {
		http.Error(w, "Name field is required", http.StatusBadRequest)
		return
	}

	response := map[string]string{"hello": name}

	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(http.StatusOK)

	json.NewEncoder(w).Encode(response)
}
  1. Run via go run app.go
  2. Try using the endpoint via
import { ofetch } from "ofetch";

const options = {
    method: 'POST',
    headers: {'Content-Type': 'application/x-www-form-urlencoded'},
    body: new URLSearchParams({
      name: 'abc'
    })
  };
  
  ofetch('http://localhost:8080/hello', options)
    .then(response => console.log(response))
    .catch(err => console.error(err));

It should error out.

Describe the bug

Form encoded post requests are not working as expected and erroring out(400).

Additional context

I tried using simple fetch and things were working as expected.

const options = {
    method: 'POST',
    headers: {'Content-Type': 'application/x-www-form-urlencoded'},
    body: new URLSearchParams({
      name: 'abc'
    })
  };
  
  fetch('http://localhost:8080/hello', options)
    .then(response => response.json())
    .then(response => console.log(response))
    .catch(err => console.error(err));

Even curl was working:

curl --request POST http://localhost:8080/hello --header 'Content-Type: application/x-www-form-urlencoded' --data name=abc

Logs

FetchError: [POST] "http://localhost:8080/hello": 400 Bad Request

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions

      0