Open
Description
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:
- 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)
}
- Run via
go run app.go
- 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