Git Product home page Git Product logo

form-urlencoded's Introduction

form-urlencoded

(c)Bumblehead, JBlashill

npm version Build Status

Returns 'x-www-form-urlencoded' string data, an encoding often used when an HTML form is submitted. Form data is serialised in this format and sent to a server.

import formurlencoded from 'form-urlencoded'
// or:
// var formurlencoded = require('form-urlencoded')

const obj = {
  str: 'val',
  num: 0,
  arr: [3, {prop: false}, 1, null, 6],
  obj: {prop1: null, prop2: ['elem']}
}

console.log(formurlencoded(obj))
// str=val&num=0&arr%5B0%5D=3&arr%5B1%5D%5Bprop%5D=false
// &arr%5B2%5D=1&arr%5B3%5D=null&arr%5B4%5D=6&obj%5Bprop
// 1%5D=null&obj%5Bprop2%5D%5B0%5D=elem

console.log(formurlencoded(obj, {
  ignorenull: true,
  skipIndex: true,
  sorted: true
}))
// arr%5B%5D=3&arr%5B%5D%5Bprop%5D=false&arr%5B%5D=1&arr
// %5B%5D=6&num=0&obj%5Bprop2%5D%5B%5D=elem&str=val

console.log(formurlencoded(obj, {
  ignoreEmptyArray: true,
  ignorenull: true,
  useDot: true,
  skipIndex: true,
  skipBracket: true
}))
// str=val&num=0&arr=3&arr.prop=false&arr=1&arr=6&obj.pr
// op2=elem

scrounge

(The MIT License)

Copyright (c) Bumblehead [email protected]

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

form-urlencoded's People

Contributors

bumblehead avatar darkman97i avatar debens avatar iambumblehead avatar iconic-engine-hito avatar jumper423 avatar kahirul avatar m14t avatar perrin4869 avatar sanva avatar scott-lc avatar stevenluan avatar tomis avatar vestride avatar wzs avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

form-urlencoded's Issues

URIError: Malformed encodeURI input

I'm seeing a "URIError: Malformed encodeURI input" error at encodeURIComponent when emoji are passed in as the value to encode(value).

It looks like the error is coming from line 7, .replace(/[^ !'()~*]/gu, encodeURIComponent), when encode(value) is called within nest on line 34, f = encode(name) + '=' + encode(value);.

The error doesn't occur on all emoji.

Here are a few emoji that have triggered the error in React Native on iOS and Android: 😎, 😅, 😍, 👀

Encoding differences with Postman

Now i can be wrong here, but i see a difference when Postman does encoding on a value P@55word which results into password=P@55word vs when this library encodes the value it results password=P%4055word which of this is right? and or if there any options flag that i am missing to get this value encoded as postman..
To verify open the code section on postman in HTML

Disable the wiki

I would suggest disabling the wiki. I was able to just create a page and am not a contributor.

Provide ES5 source?

Currently the source provided is ES6. The default config of webpack & babel-loader is not to transpile anything in node_modules. And when using ES6, this package breaks when compiling/uglifying.

Usually packages transpile their code using a postinstall command, "postinstall": "babel -d lib/ src/" and point the main field to lib. lib is in .gitignore too.

Open to this?

Using require default returns undefined in v4.5.0

With the newest release v4.5.0, the following line now returns an undefined:
const formEncode = require('form-urlencoded').default

Reverting to 4.4.2 works fine again. It seems like the changes for esm module support has broken it for CommonJS. Removing .default works fine actually: const formEncode = require('form-urlencoded') when on the latest version.

It now depends if this is a deliberate change. If yes, it would probably make more sense to bump it to v5 as it is a breaking change for any packages and projects that use .default import

Bug: Issue with encoding spaces

Bug

Repro Steps

Pass an object into the form-urlencoded function where at least one of the properties is a string and contains a space. That space will be replaced with a + when it should be %20 as when you decode a + with url encoding it is still a +.

Example:

const formurlencoded = require('form-urlencoded')

const str = formurlencoded({
  grant_type: 'grant_type:phone',
  phone_code: '585858',
  phone_number: '(318)  470-1137'
})

console.log(str)
// str will equal
// grant_type=urn%3Alyft%3Aoauth2%3Agrant_type%3Aphone&phone_code=718629&phone_number=%28318%29++470-1137
// and should be
// grant_type=urn%3Alyft%3Aoauth2%3Agrant_type%3Aphone&phone_code=718629&phone_number=%28318%29%20%20470-1137

No need for [] when skipping index for an array

When I have a multi-value attribute like

const formData = {
  name: ['apple', 'bananas']
}

and run this through formurlencoded(formData, { skipIndex: true })

then I expect this to be

name=apple&name=bananas
// in parsed form:
// name: apple
// name: bananas

but not

name%5B%5D=apple&name%5B%5D=bananas
// in parsed form:
// name[]: apple
// name[]: bananas

Option to ignore empty arrays

Hi!

I'm replacing some code using jQuery ajax method, and I find your package very useful for this endeavor — thanks a lot!

Would you consider adding an option to skip empty arrays? I can do it myself and make a PR if you want.

Best regards! :)

the change to exports.default breaks rollup, possibly other build tools

fwiw, the recent change to module.exports.default = ... breaks rollup.

i'm not entirely sure about other envs, but with rollup, you need module.exports = fn... and the default is implied. (i believe webpack is the same, though it may sniff for .default. donno.)

after this change, you need to do this to support latest release and past releases:

import { default as _formurlencoded } from 'form-urlencoded';
const formurlencoded = 'default' in _formurlencoded ? _formurlencoded.default : _formurlencoded;

module field in package.json points to a non-existent file

The "module" field in the package.json file points to a src/form-urlencoded.js file, which doesn't exists in either the repository or the npm package. This is currently conflicting with some functionality in rollup.

This field should be pointing to the esm version of the library, which is now the form-urlencoded.js file in the root folder.

Why Array data urlencoded need index number?

function arrnest(name, arr) {
    return arr.length ? filterjoin(arr.map(function (elem, index) {
        return nest(name + '[' + index + ']', elem);
    })) : encode(name + '[]');
}

Data structure:
FCartId:[1,2,3,4,5,6]

After urlencoded:
FCartId[0]:1
FCartId[1]:2
FCartId[2]:3
FCartId[3]:4
FCartId[4]:5
FCartId[5]:6

I see jQuery serialize function return:
FCartId[]:1
FCartId[]:2
FCartId[]:3
FCartId[]:4
FCartId[]:5
FCartId[]:6

Looking for you reply!

Name of the arrays always ends with []

Really, is mandatory the name of attributes of type array always ending with []?

In this section of code is forcing always to set at the end of the name of arrays attribute the []

arrnest = (name, arr) => arr.length
            ? filterjoin(arr.map((elem, index) => skipIndex
                ? nest(name + '[]', elem)
                : nest(name + '[' + index + ']', elem)))
            : encode(name + '[]'),

When I sending attributes with Jersey - JAVA - I'm doing in this way:

for (String user : users) {
    formParam.add("usersId", user);
}

The next image show data collected from server:
Selección_030

After reading some of the closed issues #8 , specially the end of the #7, I changed the code with:

formurlencoded(formData, { skipIndex: true }),

That worked nearly the expected, but the name includes always the [] at the end.
Selección_031

And here my question, something might be wrong, or my code in Jersey or [] added by your package should not be mandatory ( might be there's some RFC what forces the [] at the end if is an array? ). Or maybe both scenarios are acceptable?

I make a small improvement in the server side to working with both name format, but I will appreciate your opinion about it.

Thanks for your time.

optional formatting for nested object

Hi, Thanks for a very useful libs. However, when I tried to use the library on my project. I come into a requirement like the following

sample json:

{
   "a" : [
        {
             "aa" : 1,
             "ab" : 2
        },
        {
            "ac" : 3
        }
    ]
}

The current code will format the field name as "a[0][aa]" before the encoding.
What I need was in the format of "a[0].name" before the encoding.

I added the another option for this in my fork repo. Let me know if this is something that can be merged.

Thanks

Differences between 2.07 and 2.04

Hi, i'm having troubles with version 2.0.7 it seems to be exporting an object with { default }
I had to roll back to 2.0.4

Have this happened to you?
(im using node 8.9.4)

Brackets

How do I output obj.prop2.prop3=elm as obj[prop2][prop3]=elm.

Regex becomes broken when uglified

So UglifyJS has this tendency to replace any \uXXXX substring with the UTF-8 equivalent. However, code points such as \uDC00, \uDFFF, \uD800, \uDBFF are surrogate characters and therefore don't have a UTF-8 equivalent. UglifyJS therefore replaces these substrings with �, which turns the regex line into:

s = new RegExp(['(?:[\0-�"-&+-}�-퟿-�]|', "[�-�][�-�]|[�-�](?![�-�])|", "(?:[^�-�]|^)[�-�])"].join(""), "g"),

This regex is not the same as the regex in the source code. The �-� part which used to mean \uDC00-\uDFFF now essentially means \uFFFD-\uFFFD...

Now of course you could argue that this is something UglifyJS should fix on their end, but it has been mentioned several times and they don't seem to ever fix it. They just suggest to use the --ascii-only parameter to suppress this transformation.

I think a library such as this one will be used in a lot of projects where the source code will be uglified. People won't notice that this transformation is invalid and therefore won't use the --ascii-only parameter either.

You can fix this in the library itself by escaping the backslashes. Basically this:

encodechar = new RegExp(['(?:[\\0-\\x1F"-&\\+-\}\\x7F-\\uD7FF\\uE000-\\uFFFF]|',
    '[\\uD800-\\uDBFF][\\uDC00-\\uDFFF]|[\\uD800-\\uDBFF](?![\\uDC00-\\uDFFF])|',
    '(?:[^\\uD800-\\uDBFF]|^)[\uDC00-\\uDFFF])'].join(''), 'g')

Alternatively you can replace it with regex notation. UglifyJS won't transform those:

encodechar = /(?:[\0-\x1F"-&\+-\}\x7F-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])/g

So since this technically is not a bug on your end, you can just ignore this if you want. However, I am hoping you will apply this fix to prevent more headaches in the future.

encoded another language is wrong

Hi
i try to encode the object that include this word นาย กิตติทัต อุปพงศ์
the right encoded must be %B9%D2%C2+%A1%D4%B5%B5%D4%B7%D1%B5+%CD%D8%BB%BE%A7%C8%EC
but i got %E0%B8%99%E0%B8%B2%E0%B8%A2+%E0%B8%81%E0%B8%B4%E0%B8%95%E0%B8%95%E0%B8%B4%E0%B8%97%E0%B8%B1%E0%B8%95+%E0%B8%AD%E0%B8%B8%E0%B8%9B%E0%B8%9E%E0%B8%87%E0%B8%A8%E0%B9%8C

can you help me with this?

skipIndex usage needs a fix

When I use this module and provide an option skipIndex. I see issue with urlencoded data.

The use case that I have is for input payload like x=y&x=y, traditional body parsers convert this into a JSON as {x: [y,y]}. If I convert this into urlencoded data again using this module with option skipIndex set to true. I expect the response to be like x=y&x=y, but instead it is like x[]=y&x[]=y. Is the array indexing is still needed here? Referring the implementation where the indexing added here https://github.com/iambumblehead/form-urlencoded/blob/master/form-urlencoded.js#L27

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.