i'm trying to post a url to express and grab the the url in express from the body but it splits the url string in to different key values. what am i doing wrong? i need the string to be completed in express.
My Fetch Post:
const bodyContent = JSON.stringify({
url: "https://www.amazon.com/adidas-Womens-Ultraboost-Running-Metallic/dp/B07RFNL3PW/ref=sr_1_8?keywords=adidas ultraboost&pd_rd_r=c074b464-277c-4efb-bd29-86461b54835a&pd_rd_w=7QuQt&pd_rd_wg=VWKbv&pf_rd_p=0f7345d0-8152-4ac5-802c-50e10d235750&pf_rd_r=VG0MZMGVV1AP1WVX8B5G&qid=1647451696&refinements=p_89:Stella McCartney|adidas|adidas Originals&s=apparel&sr=1-8&wi=us-slds-sp-2-t1-a2_3"
})
fetch('http://localhost:8888/post', {
method: 'POST',
mode: 'no-cors',
body: bodyContent,
headers: {
"Accept": "application/json",
"Content-Type": "application/x-www-form-urlencoded"
}
}).then(resp => console.log(resp)).catch(err => console.log(err))
My Express setup:
const bodyParser = require('body-parser')
const express = require('express')
const app = express()
app.use(express.json())
app.use(express.urlencoded({ extended: true }))
app.post('/post', (req, res) => {
res.header("Access-Control-Allow-Origin", "*")
res.setHeader('Access-Control-Allow-Origin', "*");
res.header("Access-Control-Allow-Headers", "X-Requested-With")
console.log(req.body)
res.send(req.body)
})
Result:
{
'{"url":"https://www.amazon.com/adidas-Womens-Ultraboost-Running-
Metallic/dp/B07RFNL3PW/ref': 'sr_1_8?keywords=adidas ultraboost',
pd_rd_r: 'c074b464-277c-4efb-bd29-86461b54835a',
pd_rd_w: '7QuQt',
pd_rd_wg: 'VWKbv',
pf_rd_p: '0f7345d0-8152-4ac5-802c-50e10d235750',
pf_rd_r: 'VG0MZMGVV1AP1WVX8B5G',
qid: '1647451696',
refinements: 'p_89:Stella McCartney|adidas|adidas Originals',
s: 'apparel',
sr: '1-8',
wi: 'us-slds-sp-2-t1-a2_3"}'
}
CodePudding user response:
Change this on the front-end:
- "Content-Type": "application/x-www-form-urlencoded"
- "Content-Type": "application/json"
It is converting the = in the url to individual key-value pairs.
You are using a json anyway for the body, so this should work.
CodePudding user response:
I didn't try it but this line is looking suspicious.
app.use(express.urlencoded({ extended: true }))
Probably you don't want extended: true
. Try setting it to false.
Reference: https://expressjs.com/en/api.html#express.urlencoded